《大話設計模式》Java程式碼示例(三)之裝飾模式
阿新 • • 發佈:2018-12-17
裝飾模式(Decorator):動態地給一個物件新增一些額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活。
package decorator; /** * 裝飾模式(Decorator) * Person類 */ public class Person { private String name; public Person() {} public Person(String name) { this.name = name; } public void show() { System.out.println("裝扮的" + name); } }
package decorator; /** * 裝飾模式(Decorator) * 服飾類 */ public class Finery extends Person { protected Person component; // 打扮 public void decorate(Person component) { this.component = component; } @Override public void show() { if (component != null) { component.show(); } } } class TShirts extends Finery { public void show() { System.out.print("大T恤 "); super.show(); } } class BigTrouser extends Finery { public void show() { System.out.print("大褲頭 "); super.show(); } } class Sneakers extends Finery { public void show() { System.out.print("破球鞋 "); super.show(); } } class Suit extends Finery { public void show() { System.out.print("西裝 "); super.show(); } } class Tie extends Finery { public void show() { System.out.print("領帶 "); super.show(); } } class LeatherShoes extends Finery { public void show() { System.out.print("皮鞋 "); super.show(); } }
package decorator; /** * 裝飾模式(Decorator) * 客戶端main方法 */ public class Attire { public static void main(String[] args) { Person p0 = new Person("Kobe"); System.out.println("第一種裝扮:"); TShirts tShirts = new TShirts(); BigTrouser bigTrouser = new BigTrouser(); Sneakers sneakers = new Sneakers(); tShirts.decorate(p0); bigTrouser.decorate(tShirts); sneakers.decorate(bigTrouser); sneakers.show(); System.out.println("第二種裝扮:"); Person p1 = new Person("Allen"); Suit suit = new Suit(); Tie tie = new Tie(); LeatherShoes leatherShoes = new LeatherShoes(); leatherShoes.decorate(p1); tie.decorate(leatherShoes); suit.decorate(tie); suit.show(); } }