Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement the Decorator pattern if you can't inherit from the class you want to decorate?

Tags:

c#

This is more a design question... You can't do a decorate design pattern if:

1) The object is marked "sealed" meaning you can't extend from it. 2) or you want to override a method but its not virtual.

What can you do then? Taken that you can't change the class source code if you don't have the source code (like a 3rd party library).

like image 609
Lennie Avatar asked May 08 '10 14:05

Lennie


People also ask

Does Decorator design pattern use inheritance?

We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can't add any new functionality of remove any existing behavior at runtime - this is when Decorator pattern comes into picture.

Why would you favor the decorator pattern over inheritance?

The GoF Design Patterns book identifies two major advantages of using Decorators over subclassing: More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static (multiple) inheritance.

When would you use the Decorator design pattern?

The Decorator pattern is best when the decorators modify the behavior of the methods in the interface. A decorator can add methods, but added methods don't carry through when you wrap in another decorator.


1 Answers

Inheritance isn't necessary for a Decorator pattern. The simplest case is if the object you want to decorate implements an interface. Then your decorator can simply implement the same interface:

[   IWindow   ]
[ + Draw()    ]
---------------
  |
  +--- [   Window    ]
  |    [ + Draw()    ]
  |
  |
  +--- [ DecoratedWindow ]
       [ + Draw()        ]
       -------------------
         |
         +--- [ BorderDecorator ]
         |
         +--- [ VerticalScrollbarDecorator ]
         |
         +--- [ HorizontalScrollbarDecorator ]

Now you can just do:

IWindow w = new BorderDecorator(
             new HorizontalScrollBarDecorator(
              new VerticalScrollBarDecorator(
               new Window(80, 24))));

// This is a window with a border and scrollbars, even though
// the original Window class has no idea what those are.
w.Draw();

The specifics of what are possible will depend on the exact nature of the class you're trying to decorate.

like image 154
John Feminella Avatar answered Oct 18 '22 15:10

John Feminella