A Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically".java
裝飾模式的含義就是:「動態地爲對象添加一些附加的責任」。換句話說,Decorator模式使用組合而不是繼承來在運行時擴展對象的功能。裝飾模式也被稱爲Wrapper-包裝器模式。它是繼承的一種替代方案。app
UMLide
code 1:Person.java測試
1 package com.daike.decorator; 2
3 /**
4 * 抽象構件角色 Person 5 * @author daike 6 * 7 */
8 public interface Person { 9
10 public void show (); 11 }
code 2:GenericPerson.javaflex
1 package com.daike.decorator; 2
3 /**
4 * 具體構件角色 GenericPerson 5 * @author daike 6 * 7 */
8 public class GenericPerson implements Person{ 9
10 @Override 11 public void show() { 12 System.out.println("一個普通的人。"); 13 } 14
15 }
code 3:Tearcher.javathis
1 package com.daike.decorator; 2
3 /**
4 * 具體裝飾角色 Tearcher 5 * @author daike 6 * 7 */
8 public class Tearcher extends Decorator{ 9 public Tearcher () {} 10 public Tearcher (Person per) { 11 super(per); 12 } 13
14 @Override 15 public void show() { 16 super.show(); 17 System.out.println("我仍是一個很厲害的老師!"); 18 } 19 }
code 3:Decorator.java編碼
1 package com.daike.decorator; 2
3 /**
4 * 裝飾角色 Decorator 5 * @author daike 6 * 7 */
8 public class Decorator implements Person { 9 private Person per; 10
11 public Decorator() {} 12
13 public Decorator (Person per) { 14 this.per = per; 15 } 16 @Override 17 public void show() { 18 per.show(); 19 } 20
21 }
code 4:SuperMan.javaspa
1 package com.daike.decorator; 2
3 /**
4 * 具體裝飾角色 SuperMan 5 * @author daike 6 * 7 */
8 public class SuperMan extends Decorator{ 9
10 public SuperMan () {} 11 public SuperMan (Person per) { 12 super(per); 13 } 14 @Override 15 public void show() { 16 super.show(); 17 System.out.println("我仍是厲害的超人!"); 18 } 19 }
code 5:DecoratorTestDriver.javacode
1 package com.daike.decorator; 2
3 /**
4 * 測試類 5 * @author diake 6 * 7 */
8 public class DecoratorTestDriver { 9
10 public static void main (String[] args) { 11 Person per = new GenericPerson(); 12 Decorator teacher = new Tearcher(per); 13 Decorator superMan = new SuperMan(teacher); 14 //第一次裝飾
15 System.out.println("-------------第一次裝飾-----------------"); 16 teacher.show(); 17 //第一次裝飾
18 System.out.println("-------------第二次裝飾-----------------"); 19 superMan.show(); 20 } 21 }
運行結果:對象