设计模式|装饰者模式

image.png


代码

package com.elltor.designpattern.decorate;

public interface Component {
    void operate();
}
package com.elltor.designpattern.decorate;

public class ConcreteComponent implements Component {
    @Override
    public void operate() {
        System.out.println("ConcreteComponent operate....(origin)");
    }
}
package com.elltor.designpattern.decorate;

public class Decorator implements Component {
    protected Component component;

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


    @Override
    public void operate() {
        if(this.component!=null){
            component.operate();
        }
    }
}
package com.elltor.designpattern.decorate;

public class Decorator implements Component {
    protected Component component;

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


    @Override
    public void operate() {
        if(this.component!=null){
            component.operate();
        }
    }
}
package com.elltor.designpattern.decorate;

public class ConcreteDecoratorA extends Decorator {
    String info = "ConcreteDecoratorA";


    // 并不太好
    @Override
    public void operate() {
        super.operate();
        System.out.println("装饰一下..............");
        System.out.println("info: "+info);
    }
}
package com.elltor.designpattern.decorate;


public class ConcreteDecoratorB extends Decorator {
    String info = "ConcreteDecoratorB";

    @Override
    public void operate() {
        super.operate();
        System.out.println("装饰一下..............");
        System.out.println("info: "+info);
    }
}
package com.elltor.designpattern.decorate;

public class Main {

    public static void main(String[] args) {
        ConcreteComponent cc = new ConcreteComponent();
        System.out.println("未装饰前");
        cc.operate();

        System.out.println("\n--------------------");

        System.out.println("A装饰后");
        ConcreteDecoratorA A = new ConcreteDecoratorA();
        A.setComponent(cc);
        A.operate();

        System.out.println("\n--------------------");
        System.out.println("B装饰后");
        ConcreteDecoratorA B = new ConcreteDecoratorA();
        B.setComponent(cc);
        B.operate();
    }
}

//运行结果
未装饰前
ConcreteComponent operate....(origin)

--------------------
A装饰后
ConcreteComponent operate....(origin)
装饰一下..............
info: ConcreteDecoratorA

--------------------
B装饰后
ConcreteComponent operate....(origin)
装饰一下..............
info: ConcreteDecoratorA

如果一个类型的功能被代理的多了也就说明该类的需要重构了, 过多的使用装饰器会使类比较臃肿。