大話設計模式讀書筆記之裝飾者模式

1.定義:動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更爲靈活。
2.UML類圖
這裏寫圖片描述

3.簡單介紹:Component是定義一個對象接口,可以給這些對象動態地添加職責。ConcreteComponent是定義了一個具體的對象,也可以給這個對象添加一些職責。Decorator,裝飾抽象類,繼承了Component,從外類來擴展Component類的功能,但對於Component來說,是無需知道Decorator的存在的。至於ConcreteDecorator就是具體的裝飾者,起到給Component添加職責的功能。
4.簡單代碼實現

//裝飾者模式抽象類
package com.guo.decoratorPattern;

public abstract class Component {

    public abstract void operation();
}
//具體操作的被裝飾的類
package com.guo.decoratorPattern;

public class ConcreteComponent extends Component {

    @Override
    public void operation() {
        System.out.println("具體對象的操作。。。");
    }

}
//裝飾者抽象類
package com.guo.decoratorPattern;

public abstract class Decorator extends Component {

    private Component component;

    public Decorator(Component component) {
        super();
        this.component = component;
    }

    @Override
    public void operation() {
        if (component != null) {
            System.out.println("實際執行的是傳入的Component,被裝飾的是 :" + component.getClass().getName());
            component.operation();
        }
    }
}
//裝飾者實現類
package com.guo.decoratorPattern;

public class DecoratorComponent extends Decorator {

    public DecoratorComponent(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("此處可以添加一些裝飾類自己的行爲。。。");
    }

}
//客戶端調用示例
package com.guo.decoratorPattern;

public class DecoratorClient {

    public static void main(String[] args) {
        //實例化一個被裝飾者
        Component concreteComponent = new ConcreteComponent();
        //實例化一個裝飾者
        Component decoratorComponent = new DecoratorComponent(concreteComponent);

        decoratorComponent.operation();
    }
}

5.總結
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章