Decorator(也稱Wrapper) 屬于對象結(jié)構(gòu)型模式。
1. 意圖:動態(tài)地給一個對象添加一些額外的職責(zé)精绎。
2. 動機(jī):我們有時候只是希望給某個對象而不是整個類添加一些功能。
3. 適用性: 在不影響其他對象的情況下卖局,以動態(tài)淆攻、透明的方式給單個對象添加職責(zé)。
4. 優(yōu)點(diǎn):
? ? ? ? ? ?a 比靜態(tài)繼承更靈活
? ? ? ? ? ?b 避免在層次結(jié)構(gòu)高的類有太多的特征
5. 缺點(diǎn):
? ? ? ? ? ?a Decorator 與 Component 不一樣悼泌,Decorator是一個透明的包裝
? ? ? ? ? ?b 產(chǎn)生許多小對象
6. 結(jié)構(gòu):
7. 代碼實(shí)例:
以手機(jī)為例,手機(jī)屬于通訊工具夹界,最基本的功能就是打電話(voice call)馆里。手機(jī)又有feature phone 和 smart phone,但是我們時候會需要打vedio call可柿,或者 meeting call等等擴(kuò)展功能鸠踪。
public abstract class CommunicationTool {
? ?private static final String DESCRIPTION = "make a call through communication tool";
? ?public String getDescription() {
? ? ? ?return DESCRIPTION;
? ?}
? ?public abstract void call();
}
public abstract class Decorator extends CommunicationTool {
? ?public abstract String getDescription();
}
public class SmartPhone extends CommunicationTool {
? ?public void call() {
? ? ? ?System.out.println("make a call from smart phone");
? ?}
}
? ?public class VedioDecorator extends Decorator {
? ? ? ?private CommunicationTool mDecorator;
? ? ? ?private static final String DESCRIPTION = "a vedio call";
? ? ? ?public VedioDecorator(CommunicationTool mDecorator) {
? ? ? ? ? ?super();
? ? ? ? ? ?this.mDecorator = mDecorator;
? ? ? ?}
? ?public void call() {
? ? ? ?mDecorator.call();
? ? ? ?makeVedioCall();
? ?}
? ?private void makeVedioCall() {
? ? ? ?System.out.println(DESCRIPTION);
? ?}
? ?@Override
? ?public String getDescription() {
? ? ? ?return DESCRIPTION;
? ?}
}
? ?public class MeetingDecorator extends Decorator {
? ? ? ?private static final String DESCRIPTION = "a meeting call";
? ? ? ?private CommunicationTool mDecorator;
? ? ? ?public MeetingDecorator (CommunicationTool decorator) {
? ? ? ? ? ? ?mDecorator = decorator;
? ? ? ?}
? ?@Override
? ?public String getDescription() {
? ? ? ?return DESCRIPTION;
? ?}
? @Override
? ?public void call() {
? ? ? ?mDecorator.call();
? ? ? ?makeMeetingCall();
? ?}
? ?private void makeMeetingCall() {
? ? ? ?System.out.println(DESCRIPTION);
? ?}
}
public class TestMachine {
? ? public static void main(String[] args) {
? ? ? ? CommunicationTool mPhone = new SmartPhone();
? ? ? ? Decorator mDecorator = new VedioDecorator(mPhone);
? ? ? ? mDecorator = new MeetingDecorator(mDecorator);
? ? ? ? mDecorator.call();
? ? }
}
8. 真實(shí)案例:
? ? ? ? ? ?a 許多面向?qū)ο蟮挠脩艚缑婀ぞ呤褂醚b飾為窗口組件添加圖形修飾
? ? ? ? ? ?b Java I/O,F(xiàn)ileInputStream BufferedInputStream LineNumberInputStream
9. 相關(guān)模式:
Adapter模式:Decorator模式不同于Adapter模式复斥,因?yàn)檠b飾僅改變對象的職責(zé)而不改變它的借口营密;而適配器模式給對象一個全新的接口。
Composite模式:可以將裝飾視為一個退化的目锭、僅有一個組件的組合评汰,而裝飾的目的不在于對象的聚集。
Strategy模式:用一個裝飾你可以改變對象的外表痢虹;而Strategy模式使得你可以改變對象的內(nèi)核被去。
10. 相關(guān)設(shè)計原則: 開放--關(guān)閉原則
類應(yīng)該對擴(kuò)展開放,對修改關(guān)閉