【发布时间】:2014-03-25 21:29:29
【问题描述】:
也许我在这里遗漏了一些东西,我承认我的 OO 技能不是我想要的,但是看着这个 example of the decorator pattern,我注意到 UML 声明装饰器既是 is-a组件和有一个组件。这让我有点困惑,因为两者兼而有之似乎是多余的,事实上,当我测试“真实世界”代码found here,并将装饰器类修改为如下所示:
abstract class Decorator /*: LibraryItem*/ {
protected LibraryItem libraryItem;
// Constructor
public Decorator(LibraryItem libraryItem) {
this.libraryItem = libraryItem;
}
public /* override */ void Display() {
libraryItem.Display();
}
}
...
class Borrowable : Decorator {
protected List<string> borrowers = new List<string>();
// Constructor
public Borrowable(LibraryItem libraryItem) : base(libraryItem) { }
public void BorrowItem(string name) {
borrowers.Add(name);
libraryItem.NumCopies--;
}
public void ReturnItem(string name) {
borrowers.Remove(name);
libraryItem.NumCopies++;
}
public new /*override*/ void Display() {
base.Display();
foreach (string borrower in borrowers) {
Console.WriteLine(" borrower: " + borrower);
}
}
}
我在这里所做的只是通过注释掉“:LibraryItem”来删除is-a关系,但通过保留“protected LibraryItem libraryItem;”来保持has-a关系。我还注释掉了 Display 方法上的覆盖,用 new 关键字替换了一个。据我所知,这与原始代码一样有效。
我在这里遗漏了什么吗?装饰器真的有必要从组件继承吗? UML 图和实现的代码肯定会建议这样做,但我很好奇是否有一些我没有看到或没有正确解决的问题。
想法?
【问题讨论】:
-
无论我看你的代码多久,我都看不到这里的装饰器。装饰器的基本思想是将相同的接口递归应用到装饰对象。这里没有这样的东西。
-
那是因为我提供的代码只是对上述链接之一中提供的真实装饰器的修改。 :)
标签: c# design-patterns decorator