裝飾者模式(Decorator):動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾者模式比生成子類更為靈活。 1.定義介面,可以動態的給對象添加職責。 2.實現這個介面 3.裝飾類 4.具體實現的裝飾類 5.測試用例: 6.運行結果: ...
裝飾者模式(Decorator):動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾者模式比生成子類更為靈活。
1.定義介面,可以動態的給對象添加職責。
1 package com.lujie; 2 3 public interface SuperPerson { 4 //定義一個介面,可以動態的給對象添加職責 5 public abstract void show() ; 6 }
2.實現這個介面
1 package com.lujie; 2 3 public class Person implements SuperPerson{ 4 private String name; 5 public Person() { 6 // TODO Auto-generated constructor stub 7 } 8 public Person(String name) { 9 this.name=name; 10 } 11 //具體對象的操作 12 public void show() { 13 System.out.println("裝飾者:"+name); 14 } 15 }
3.裝飾類
1 package com.lujie; 2 3 public class Finery extends Person{ 4 protected Person component; 5 //設置component 6 public void Decorate(Person component) { 7 this.component=component; 8 } 9 //重寫show(),實際執行的是component的show()操作 10 public void show() { 11 if(component!=null){ 12 component.show(); 13 } 14 } 15 16 }
4.具體實現的裝飾類
1 package com.lujie; 2 3 public class Shoes extends Finery{ 4 //首先執行本類的功能,再運行原Component的show(),相當於對原Component進行了裝飾 5 public void show() { 6 System.out.println("皮鞋"); 7 super.show(); 8 } 9 }
1 package com.lujie; 2 3 public class Suit extends Finery{ 4 //首先執行本類的功能,再運行原Component的show(),相當於對原Component進行了裝飾 5 public void show() { 6 System.out.println("西裝"); 7 super.show(); 8 } 9 }
package com.lujie; //具體服飾類 public class TShirts extends Finery{ //首先執行本類的功能,再運行原Component的show(),相當於對原Component進行了裝飾 public void show() { System.out.println("大體恤"); super.show(); } }
1 package com.lujie; 2 3 public class WearSneakers extends Finery{ 4 public void show() { 5 System.out.println("破球鞋"); 6 super.show(); 7 } 8 }
5.測試用例:
1 package com.lujie; 2 3 public class PersonShowMain { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Person person=new Person("小明"); 8 System.out.println("第一種裝扮:"); 9 WearSneakers wSneakers=new WearSneakers(); 10 BigTrouser bigTrouser=new BigTrouser(); 11 TShirts tShirts=new TShirts(); 12 //裝飾過程 13 wSneakers.Decorate(person); 14 bigTrouser.Decorate(wSneakers); 15 tShirts.Decorate(bigTrouser); 16 tShirts.show(); 17 //裝飾過程二 18 System.out.println("第二種裝扮:"); 19 Suit suit=new Suit(); 20 wSneakers.Decorate(person); 21 bigTrouser.Decorate(wSneakers); 22 suit.Decorate(bigTrouser); 23 suit.show(); 24 } 25 26 }
6.運行結果: