提升從Wikipedia這個例子:如何在不迫使某人重新實現一切的情況下實現裝飾器模式?
// the Window interface
interface Window {
public void draw(); // draws the Window
public String getDescription(); // returns a description of the Window
}
// implementation of a simple Window without any scrollbars
class SimpleWindow implements Window {
public void draw() {
// draw window
}
public String getDescription() {
return "simple window";
}
}
// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
protected Window decoratedWindow; // the Window being decorated
public WindowDecorator (Window decoratedWindow) {
this.decoratedWindow = decoratedWindow;
}
public void draw() {
decoratedWindow.draw();
}
}
我怎麼會,例如,允許用戶實現一個裝飾draw
但不getDescription
一個裝飾?在我的實際代碼中,有5種可能的裝飾方法。
我看到它的方式,我有3個選項:
- 把接口上的所有5種方法。缺點是這將迫使他們實施4種方法,只是簡單地稱之爲父母。
- 創建5個接口,每個方法一個接口。有點笨拙。
- 根本不要使用接口。失去設計合同。
還有其他的選擇嗎?如果不是,上述哪一項將是最佳選擇?
我正在使用PHP。
對不起,我應該指定,我正在使用PHP。 – ryeguy 2010-10-25 17:22:17