views:

118

answers:

2

The decorator design pattern is a very good solution for extending a class functionality. For instance if I want pre and post processing methods on an existing class method I can create a decorator and override the existing method in the base class and call my pre and post processing methods respectively.

My question here is, the requirement stated above will seldom arise during application design. I cannot mark all the methods I create as virtual so that they can be overridden by a decorator. Hence, I will have to resort to method hiding.

Is there a better way of designing my classes so that in situations where I want to override any methods it can be done in the best possible manner.

+1  A: 

have you thought about using aspects(AOP) ? -Added after you wrote the comment: You could take a look at the log4postsharp project and see how they are using attributes on the method. Log4PostSharp

If you compile and and open the dll using f.ex Reflector you will see that the pre- and post-actions are added runtime.

-such behavior can also be added using xml-configs

ThorHalvor
Can you provide me an example to do the above using AOP concepts.
Hemanshu Bhojak
i added more info in the answer above..
ThorHalvor
A: 

Usually when I decorate a class I do it via composition, not inheritance. That way you don't need to override anything.

Jim Arnold
You still need to extract an interface definition which your decorator class (as well as the decorated class) may implement, otherwise this won't generally work.
Konrad Rudolph
Of course. I habitually hide concrete classes behind role-based interfaces.
Jim Arnold