装饰器模式——结构型

81 阅读1分钟

1.白话文定义

在不想增加更多子类的情况下对功能进行扩展,动态的给一个类添加一些额外的功能,可以采用装饰器模式。

2.角色

1.抽象构件类:具体构件和抽象装饰器类的共同父类,声明类在具体构件汇总实现的方法;

2.具体构件:抽象构件类的子类,用于定义具体的构件对象,装饰器可以给它增加额外的职责;

3.抽象装饰器类:抽象构件类的子类;维护一个指向抽象构件的引用;

4.具体装饰器类:抽象装饰器的实现类,负责添加新职责。

3.类图

image.png

4.代码实现

  • 抽象构件类
public interface Component {

    void operation();
}
  • 具体构件
public class ConcreteComponent implements Component{
    @Override
    public void operation() {
        System.out.println("被装饰方法");
    }
}
  • 抽象装饰器类
public abstract class Decorator implements Component {

    private Component component;

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

    @Override
    public void operation() {
        component.operation();
    }
}
  • 具体装饰器类
public class ConcreteDecoratorA extends Decorator {
    
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    public void newMethod() {
        System.out.println("装饰器扩展新方法");
    }

    @Override
    public void operation() {
        System.out.println("前置装饰----");
        super.operation();
        System.out.println("后置装饰---");
    }
}
  • 客户端调用者
public class Main {

    public static void main(String[] args) {

        Component component = new ConcreteComponent();
        component.operation();

        ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(component);
        concreteDecoratorA.operation();
        concreteDecoratorA.newMethod();
    }
}
  • 测试结果

image.png

5.优点

使用不同的具体装饰器类以及装饰器类的排列组合,可以创造出更多的不同的行为组合,原有的代码符合开闭原则。

6.缺点

随着子类的增多,可能造成类膨胀。

7.参考

装饰器模式