裝飾器和虛擬方法 (Decorators and Virtual Methods)


問題描述

裝飾器和虛擬方法 (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 BhojakThorHalvorJim Arnold)

參考文件

  1. Decorators and Virtual Methods (CC BY‑SA 3.0/4.0)

#ooad #design-patterns #C#






相關問題

接口實現是否應該獨立 (Should Interface implementations be independent)

當我們有不同的回報類型時實現策略模式 (Achieve strategy pattern when we have different return type)

抽象VS信息隱藏VS封裝 (Abstraction VS Information Hiding VS Encapsulation)

應用程序中jQuery表單綁定代碼的最佳實踐 (Best practices with jQuery form binding code in an application)

耦合與內聚 (Coupling and cohesion)

什麼時候應該在C ++中使用類與結構? (When should you use a class vs a struct in C++?)

What is an anti-pattern? (What is an anti-pattern?)

如何根據編程代碼顯示聚合? (How to Show Aggregation in terms of A Programming Code?)

協調 MVP 三元組 (Coordinating MVP triads)

裝飾器和虛擬方法 (Decorators and Virtual Methods)

設計和建築有什麼區別? (What is the difference between Design and Architecture?)

特定時間段有效的業務規則——如何有序管理 (Business rules that are valid for specific time span – how to manage in an orderly manner)







留言討論