【設計模式】九、裝飾器模式

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 /**
 5  * 功能:這個是咱們裝飾器的基類,用來生成被裝飾類和裝飾器類
 6  * 時間:2016年2月25日上午10:05:37
 7  * 做者:cutter_point
 8  */
 9 public abstract class Component
10 {
11     //這個方法就是咱們裝飾器要進行裝飾的操做
12     public abstract void tuo();
13 }

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 /**
 5  * 功能:動態地給一個對象添加一些額外的職責。就增長功能來講裝飾器模式比生成子類更加靈活
 6  *         裝飾器就是用裝飾器類來對咱們的私有成員(裝飾對象)進行相應的擴展功能
 7  * 適用:在不影響其餘對象的狀況下,以動態、透明的方式給單個對象添加職責
 8  *         處理那些能夠撤銷的職責
 9  * 時間:2016年2月25日上午9:45:43
10  * 做者:cutter_point
11  */
12 public class Person extends Component
13 {
14     private String name;
15     
16     public Person(String name)
17     {
18         this.name = name;
19     }
20 
21     @Override
22     public void tuo()
23     {
24         System.out.print(this.name + "準備上牀睡覺\t");
25     }
26 }

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 
 5 /**
 6  * 功能:裝飾器基類,用來對相應的對象進行裝飾
 7  * 時間:2016年2月25日上午10:15:02
 8  * 做者:cutter_point
 9  */
10 public abstract class Decorator extends Component
11 {
12     protected Component component;
13 
14     public Decorator(Component component)
15     {
16         this.component = component;
17     }
18     
19     @Override
20     public void tuo()
21     {
22         if(component != null)
23             component.tuo();
24     }
25 
26 }

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 /**
 5  * 功能:對於一個操做,上衣
 6  * 時間:2016年2月25日上午10:18:28
 7  * 做者:cutter_point
 8  */
 9 public class Shangyi extends Decorator
10 {
11     //構造函數
12     public Shangyi(Component component)
13     {
14         super(component);
15     }
16     
17     @Override
18     public void tuo()
19     {
20         super.tuo();
21         System.out.print("脫上衣\t");
22     }
23 }

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 /**
 5  * 功能:對應褲子操做
 6  * 時間:2016年2月25日上午10:49:03
 7  * 做者:cutter_point
 8  */
 9 public class Kuzhi extends Decorator
10 {
11 
12     public Kuzhi(Component component)
13     {
14         super(component);
15     }
16 
17     @Override
18     public void tuo()
19     {
20         super.tuo();
21         System.out.print("脫掉褲子\t");
22     }
23 
24 }

 

 1 package com.shejimoshi.structural.Decorator;
 2 
 3 
 4 /**
 5  * 功能:裝飾器模式
 6  * 時間:2016年2月25日上午11:13:55
 7  * 做者:cutter_point
 8  */
 9 public class Test
10 {
11     public static void main(String[] args)
12     {
13         Component person = new Person("cutter_point");
14         Decorator shangyi = new Shangyi(person);
15         shangyi.tuo();
16         System.out.println();
17         Decorator kuzhi = new Kuzhi(person);
18         kuzhi.tuo();
19     }
20 }

測試結果:java

cutter_point準備上牀睡覺	脫上衣	
cutter_point準備上牀睡覺	脫掉褲子	
相關文章
相關標籤/搜索