设计模式之装饰模式【Decorator Pattern】

装饰模式(Decorator Pattern)也称包装模式(Wrapper Pattern),结构型设计模式,主要用一种对客户端透明的方式来动态地扩展对象的功能。

1、定义

动态地给一个对象添加额外的职责。就增加功能来说,装饰模式比生成子类更为灵活。

2、使用场景

需要动态地扩展类的功能时。

3、UML图

4、代码示例

被装饰组件类:

public interface Component {

    public void operate();
}

public class ConcreteComponent implements Component {

    public void operate() {
        //具体功能逻辑
        System.out.println("ConcreteComponent operate");
    }
}

装饰者:

//装饰器接口
public abstract class Decorator implements Component {

    //持有一个待包装的对象
    private Component component;

    //必要的构造方法,需传入待包装对象
    public Decorator(Component component) {
        this.component = component;
    }

    public void operate() {
        //可以在调用前后执行一些附加动作
        component.operate();
    }
}

//具体装饰者A,向组件对象添加职责
public class ConcreteDecoratorA extends Decorator {

    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    public void operate() {
        //添加附加动作
        operationA();

        super.operate();

        operationA();
    }

    //需要添加的职责方法A
    public void operationA() {
        System.out.println("装饰方法A");
    }

    //需要添加的职责方法B
    public void operationB() {
        System.out.println("装饰方法B");
    }
}

//具体装饰者B,向组件对象添加职责
public class ConcreteDecoratorB extends Decorator {

    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    public void operate() {
        //装饰方法1和2可在前调用也可在后调用
        operation1();
        super.operate();
    }

    //需要添加的职责方法1
    public void operation1() {
        System.out.println("装饰方法1");
    }

    //需要添加的职责方法2
    public void operation2() {
        System.out.println("装饰方法2");
    }
}

客户端调用:

public class Client {

    public static void main(String[] args) {
        //构造被装饰的对象
        Component component = new ConcreteComponent();

        //装饰者A
        Decorator decoratorA = new ConcreteDecoratorA(component);
        decoratorA.operate();

        System.out.print("\n");

        //装饰者B
        Decorator decoratorB = new ConcreteDecoratorB(component);
        decoratorB.operate();
    }
}

调用结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/iluojie/article/details/80399702