设计模式——装饰器模式

设计模式——装饰器模式

一、基本概念

1. 定义

修饰模式,是面向对象编程领域中,一种动态地往一个类中添加新的行为的设计模式。就功能而言,修饰模式相比生成子类更为灵活,这样可以给某个对象而不是整个类添加一些功能。

2. 优缺点

优点

  • 是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用;
  • 通过使用不用装饰类及这些装饰类的排列组合,可以实现不同效果;
  • 装饰器模式完全遵守开闭原则。

缺点

  • 装饰器模式会增加许多子类,过度使用会增加程序得复杂性。

3. 结构

  • 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象;
  • 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责;
  • 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能;
  • 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

image-20210301214602501

二、代码实现

抽象构件角色

1
2
3
interface Component {
    public void operation();
}

具体构件角色

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package pers.designPattern.decorator;

public class ConcreteComponent implements Component {
    public ConcreteComponent (){
        System.out.println("创建具体的构建角色...");
    }

    @Override
    public void operation() {
        System.out.println("原有功能!");
    }
}

抽象装饰角色

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Decorator implements Component {
    private Component component;

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

    @Override
    public void operation() {
        component.operation();
    }
}

具体装饰角色

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addFunction();
    }

    public void addFunction() {
        System.out.println("额外功能!");
    }
}

客户类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package pers.designPattern.decorator;

public class DecoratorClient {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component.operation();
        System.out.println("--------------");
        Component component1 = new ConcreteDecorator(component);
        component1.operation();
    }
}

运行结果:

创建具体的构建角色...
原有功能!
--------------
原有功能!
额外功能!

参考:

Licensed under CC BY-NC-SA 4.0
最后更新于 May 16, 2024 11:09 +0800
使用 Hugo 构建
主题 StackJimmy 设计