今天學習了裝飾模式,做個筆記。。裝飾模式的基礎概念可以參考:https://blog.csdn.net/cjjky/article/details/7478788
這里,就舉個簡單例子
孫悟空有72變,但是它平時是猴子,遇到情況下,它可以變成蝴蝶等等
因此提供的對象接口為:SunWukong
package com.designmodel.decorator;public interface SunWukong {void change(); }
然后是一個具體的對象:Monkey
package com.designmodel.decorator;public class Monkey implements SunWukong {public void selfIntroduce() {System.out.println("我是孫悟空, 我有72變");}@Overridepublic void change() {System.out.println("我變");}}
接下來是裝飾抽象類:Transformations
package com.designmodel.decorator;public class Transformations implements SunWukong {private SunWukong swk;public Transformations(SunWukong swk) {super();this.swk = swk;}@Overridepublic void change() {swk.change();}}
最后是兩個具體的裝飾對象:
package com.designmodel.decorator;public class XiangFei extends Transformations {public XiangFei(SunWukong swk) {super(swk);}public void nowIs() {System.out.println("我現在變成了香妃");} }
package com.designmodel.decorator;public class ButterFly extends Transformations {public ButterFly(SunWukong swk) {super(swk);}public void nowIs() {System.out.println("我現在變成了蝴蝶");} }
客戶端測試:
package com.designmodel.decorator;public class MainApp {public static void main(String[] args) {Monkey monkeyKing = new Monkey();monkeyKing.selfIntroduce();System.out.println("我要變了...");XiangFei xf = new XiangFei(monkeyKing);xf.nowIs();
System.out.println("我繼續變...");
ButterFly bf = new ButterFly(monkeyKing);
bf.nowIs();} }
輸出結果:
我是孫悟空, 我有72變
我要變了...
我現在變成了香妃
我繼續變...
我現在變成了蝴蝶
?
裝飾模式就是這個意思。。。