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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With