One of the patterns in developmentor's "Code Smarter with design patterns in .NET course" is the decorator pattern. The decorator pattern allows you to extend functionality at runtime, this works if the client is written in terms of an abstract type. Using the class hierarchy below the client would be written in terms of the Component class. The code wishing to call the client has been given an instance of ConcreteComponent, but it wants to extend the functionality of that object, in order to do this it must create another object that looks like what the client is expecting. This is where the decorator comes in, the component decorator class below is compatible with the client since it also derives from Component.
The componentDecorator class is a null decorator it simply supports the ability to wrap an object of type Component, and when any of its methods are invoked the call is simply passed on to the wrapped object. Since it has no real functionality it is also declared abstract. Each of the types DecoratorOne and DecoratorTwo overrride only the methods they wish to extend, the methods they do not wish to extend are simply handled by the base class ComponentDecorator and forwarded to the wrapped object. Before calling the client a decorator object is created, and is given the object it is to decorate, in this case something of type component. It is now this decorated object that is passed into the client.
The building of the ComponentDecorator class can become very tedious if the Component class has lots of methods that need to be implemented. This week I finally got around to writing some code that via reflection and the CodeDom classes that will generate the base decorator class, saving a reasonable amount of time and effort.
Post a Comment