The Decorator design pattern is used to dynamically add additional behavior to an object. In addition, by using interfaces, a decorator can be used to unify types in a manner similar to multiple inheritance.
Let’s take an example – suppose you have two objects, called
Lizard, that you want to put into a Decorator:
Since a decorator cannot be inheriting from both of these classes, we can use the Extract Interface in-place refactoring (Ctrl+Shift+R) for both of these objects to get their interfaces:
Calling this refactoring pops up a window asking us which members should appear in the interface:
After we do this for both our classes, we end up with the following code:
With these interfaces, we can make a decorator. First, we declare a class called Dragon, indicating that it implements both IBird and ILizard:
Now for the aggregated members. The easiest thing to do is to declare both of these as fields first, i.e.:
Now, we can use ReSharper to initialize both of these fields from constructor parameters:
After this, our class will look as follows:
And now for the finishing touch – we want to generate delegating members for both
lizard. This is easy – we simply open the Generate menu and choose Delegating Members:
ReSharper then asks us which members we need to delegate:
And here is the end result:
That’s it! Our decorator is ready.