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

装饰器模式(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();
    }
}

输出结果展示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值