裝飾器模式

裝飾器模式

簡單的說,裝飾器模式可能動態的給一個對象增加額外的功能。

就像人類通過各種服飾來打扮自己一樣,對象通過裝飾器模式打扮自己,從而擁有更多功能。

先看下裝飾器模式的類圖:

UML類圖

這裏寫圖片描述

圖1 裝飾器模式類圖

類圖中的Component是一個接口,ConcreteComponent是將要被裝飾的具體類。Decorator是裝飾器基礎抽象類,該抽象類實現了Component接口。Decorator有兩個具體的裝飾器類,這兩個裝飾器類實現了不同的裝飾效果。看下實現代碼:

代碼實現

Component類

/**
 * <p>文件描述: 需要被裝飾的類的接口</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:50
*/
public interface Component {
    void operation();
}

ConcreteComponent類

/**
 * <p>文件描述: 需要被裝飾的具體類</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:52
*/
public class ConcreteComponent implements Component {

    @Override
    public void operation() {
        System.out.println("我是需要被裝飾的類");
    }
}

Decorator類

/**
 * <p>文件描述: 裝飾器基礎抽象類</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:55
*/
public abstract class Decorator implements Component {

    private Component component;

    @Override
    public void operation() {
        if (component != null) {
            component.operation();
        }
    }

    public void setComponent(Component component) {
        this.component = component;
    }
}

ConcreteDecoratorA類

/**
 * <p>文件描述: 具體裝飾器A</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:56
*/
public class ConcreteDecoratorA extends Decorator {

    @Override
    public void operation() {
        System.out.println("通過裝飾器A裝飾");
        super.operation();
        System.out.println("裝飾器A裝飾完成");
    }
}

ConcreteDecoratorB類

/**
 * <p>文件描述: 具體裝飾器B</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:58
*/
public class ConcreteDecoratorB extends Decorator {

    @Override
    public void operation() {
        System.out.println("通過裝飾器B裝飾");
        super.operation();
        System.out.println("裝飾器B裝飾完成");
    }
}

DecoratorDemo類

/**
 * <p>文件描述: 裝飾器模式Demo類</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:59
*/
public class DecoratorDemo {

    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        //通過裝飾器A裝飾
        Decorator decoratorA = new ConcreteDecoratorA();
        decoratorA.setComponent(component);
        decoratorA.operation();
        //通過裝飾器B裝飾
        Decorator decoratorB = new ConcreteDecoratorB();
        decoratorB.setComponent(component);
        decoratorB.operation();
    }
}

Demo類輸出結果

通過裝飾器A裝飾
我是需要被裝飾的類
裝飾器A裝飾完成
通過裝飾器B裝飾
我是需要被裝飾的類
裝飾器B裝飾完成
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章