Andy's observations as he continues to attempt to know all that is .NET...

Saturday, May 03, 2008

CodeGen for base decorator

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. 

image

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.

The code can be found

No comments:

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...