views:

96

answers:

3

I think a classic example is that the Window class can have a Border decorator and a ScrollBar decorator in the GoF book.

What are some situations you think, know of, in which the Decorator Pattern solves the problem really well?

+2  A: 

The java.io package.

Brandon E Taylor
Well it's a powerful api, but when you first start on it it's overwhelming and looks like an OO overflow.
André
@Andre- agreed. Interestingly .NET System.IO API uses the same patterns but in .NET 2.0 they added a lot of helpful methods like File.ReadAllLines. Brad Abrams has quite an interesting example of the API differences- http://blogs.msdn.com/brada/archive/2005/12/27/507624.aspx. In some scenarios the Decorator pattern leads to confusion.
RichardOD
+2  A: 

Anything that is abstractable to an extendable root upon which you have to define different overlapping and interchangeable behaviors:

  • Windows and borders, scrollbars and menubars
  • Musical instruments (audio waves) and effects (flanger, wah-wah, and so on)
  • NPC and weaponry

and so on...

Vinko Vrsalovic
+1  A: 

I've used the Decorator pattern for managing complex roles.

Example off the top of my head:

public abstract class DecoratedUser : User
{
  protected User _decoratedUser;
  public DecoratedUser(User decoratedUser)
  {
    _decoratedUser = decoratedUser;
  }

  public abstract List<Permissions> GetPermissions;
}

public EditorUser : DecoratedUser
{
  public EditorUser(User decoratedUser)
    : base(decoratedUser)
  {}

  public override List<Permissions> GetPermissions
  {
    // return previous permissions + editor permissions
  }
}

public ModeratorUser : DecoratedUser
{
  public ModeratorUser(User decoratedUser)
    : base(decoratedUser)
  {}

  public override List<Permissions> GetPermissions
  {
    // return previous permissions + moderator permissions
  }
}
Kevin Swiber