设计模式-结构模式-装饰模式

本文详细介绍了装饰模式,一种在运行时动态给对象添加额外职责的结构型设计。通过组件接口、抽象装饰器和具体装饰器的示例,展示了如何灵活地扩展已有组件的功能。
摘要由CSDN通过智能技术生成

装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式。

 

//首先,定义一个组件接口:
public interface Component {
    void operation();
}
//然后,创建一个实现了该接口的具体组件类
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}
//接下来,创建一个抽象装饰器类,它实现了相同的接口并持有一个组件对象的引用:
public abstract class Decorator implements Component {
    protected Component component;

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

    @Override
    public void operation() {
        component.operation();
    }
}
//最后,创建具体装饰器类,继承自抽象装饰器并添加额外功能:
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

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

    public void addedFunctionalityA() {
        System.out.println("Added functionality A");
    }
}

public class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

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

    public void addedFunctionalityB() {
        System.out.println("Added functionality B");
    }
}
现在,你可以创建客户端代码来展示如何使用装饰器:
public class DecoratorPatternExample {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();

        System.out.println("Operation of ConcreteComponent:");
        component.operation();

        System.out.println("\nDecorating with ConcreteDecoratorA:");
        component = new ConcreteDecoratorA(component);
        component.operation();

        System.out.println("\nDecorating with ConcreteDecoratorB:");
        component = new ConcreteDecoratorB(component);
        component.operation();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值