装饰器模式详解和实现(设计模式 二)

装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你动态地将对象添加到现有对象中,以提供额外的功能,同时又不影响其他对象。

实现示例

1.定义一个接口或抽象类,表示被装饰对象的公共接口

//抽象类组件类
public interface Component {
    void operation();
}

2、创建一个具体的实现类,实现该接口(也就是初始功能的类)

//具体组件类
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("执行原始操作");//原始功能
    }
}

3、创建一个装饰器类,实现与被装饰对象相同的接口,并持有一个对被装饰对象的引用

//装饰器类:指向抽象组件引用
public abstract class Decorator implements Component {
    //引用:抽象组件
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }
    
    @Override
    public void operation() {
        component.operation();//原始功能
    }
}

4、创建具体的装饰器类,通过在装饰器类中添加额外的功能来扩展被装饰对象的行为(添加新功能)

//具体装饰器类A
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();//原始功能
        System.out.println("添加额外功能A");
    }
}
//具体装饰器类B
public class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("添加额外功能B");
    }
}

5、使用新功能(既能使用使用原始功能、也能使用新功能)

public class Main {
    public static void main(String[] args) {
        Component component=new ConcreteComponent();
        //执行原始操作
        component.operation();
        System.out.println("--------------------------");

        //执行额外操作A(包含原始操作)
        Component componentA=new ConcreteDecoratorA(new ConcreteComponent());
        componentA.operation();
        System.out.println("--------------------------");

        //同时执行额外操作A和B(嵌套)
        Component componentB=new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent()));
        componentB.operation();
    }
}

输出结果展示
装饰器模式详解和实现(设计模式 二)_第1张图片

你可能感兴趣的:(设计模式,装饰器模式,java,开发语言)