天天看點

裝飾者模式

一.裝飾者模式

定義:裝飾模式是在不改變原類檔案和不使用繼承的情況下,動态的擴充一個對象的功能。(一個類包裹被增強類)

目的:在不改變原檔案條件下對類進行增強。

優點:1.動态增強

           2.不改變原檔案,不使用繼承

           3.可以疊加裝飾

缺點:使類增多,結構變複雜。

類圖:

裝飾者模式

代碼:

被增強類接口

1. public interface Component {
2. 
3. void method();
4. 
5. }      

被增強類實作

1. public class ConcreteComponent implements Component{
2. 
3. public void method() {
4.         System.out.println("原來的方法");
5.     }
6. 
7. }      

增強類抽象類

1. public abstract class Decorator implements Component{
2. 
3. protected Component component;
4. 
5. public Decorator(Component component) {
6. super();
7. this.component = component;
8.     }
9. 
10. public void method() {
11.         component.method();
12.     }
13. 
14. }      

增強類實作A

1. public class ConcreteDecoratorA extends Decorator{
2. 
3. public ConcreteDecoratorA(Component component) {
4.         super(component);
5.     }
6. 
7. public void methodA(){
8.         System.out.println("被裝飾器A擴充的功能");
9.     }
10. 
11. public void method(){
12.         System.out.println("針對該方法加一層A包裝");
13.         super.method();
14.         System.out.println("A包裝結束");
15.     }
16. }      

增強類實作B

1. public class ConcreteDecoratorB extends Decorator{
2. 
3. public ConcreteDecoratorB(Component component) {
4.         super(component);
5.     }
6. 
7. public void methodB(){
8.         System.out.println("被裝飾器B擴充的功能");
9.     }
10. 
11. public void method(){
12.         System.out.println("針對該方法加一層B包裝");
13.         super.method();
14.         System.out.println("B包裝結束");
15.     }
16. }      

調用

1. public class Main {
2. 
3. public static void main(String[] args) {
4.         Component component =new ConcreteComponent();//原來的對象
5.         System.out.println("------------------------------");
6.         component.method();//原來的方法
7.         ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(component);//裝飾成A
8.         System.out.println("------------------------------");
9.         concreteDecoratorA.method();//原來的方法
10.         concreteDecoratorA.methodA();//裝飾成A以後新增的方法
11.         ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(component);//裝飾成B
12.         System.out.println("------------------------------");
13.         concreteDecoratorB.method();//原來的方法
14.         concreteDecoratorB.methodB();//裝飾成B以後新增的方法
15.         concreteDecoratorB = new ConcreteDecoratorB(concreteDecoratorA);//裝飾成A以後再裝飾成B
16.         System.out.println("------------------------------");
17.         concreteDecoratorB.method();//原來的方法
18. //調用父類的構造方法時,傳入的是concreteDecoratorA的類,是以super.method調用到了concreteDecoratorA中類的method,實作了兩次裝飾
19.         concreteDecoratorB.methodB();//裝飾成B以後新增的方法
20.     }
21. }      

結果:

裝飾者模式

繼續閱讀