問題描述
裝飾器和虛擬方法 (Decorators and Virtual Methods)
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:
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
方法 2:
Usually when I decorate a class I do it via composition, not inheritance. That way you don't need to override anything.
(by Hemanshu Bhojak、ThorHalvor、Jim Arnold)