侧边栏壁纸
博主头像
Elltor

用心发现生活,积极面对工作、事,坚持每天让自己进步一点。

  • 累计撰写 164 篇文章
  • 累计创建 1 个标签
  • 累计收到 10 条评论

目 录CONTENT

文章目录

设计模式|装饰者模式

Elltor
2020-10-29 / 0 评论 / 0 点赞 / 57 阅读 / 2,144 字

结构图

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

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

0

评论区