GoF设计模式(七) - 装饰者模式

前言

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

装饰者模式分为如下几个部分:

(1)Component:主体(装饰的主体是什么)(抽象的的构建对象)

(2)ConcreteComponent:抽象构件对象的子类,用来定义具体的构件对象

(3)Decorator:装饰者,继承了Component,从外类来扩展Component类的功能

(4)ConcreteDecorator:具体装饰类,实现了抽象装饰类,负责构建新的职责

具体实现

public interface Component {
    void operation();
}
public class ConcreteComponent implements Component {

    @Override
    public void operation() {
        System.out.println("具体对象的操作");
    }

}
public abstract class Decorator implements Component {

    private Component component;

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

    @Override
    public void operation() {
        if(component != null) {
            this.component.operation();
        }
    }

}
public class ConcreteDecoratorA extends Decorator {

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

    private void method1() {
        System.out.println("method1 修饰");
    }

    @Override
    public void operation() {
        super.operation();
        this.method1();

    }

}
public class ConcreteDecoratorB extends Decorator {

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

    private void method2() {
        System.out.println("method2 修饰");
    }

    @Override
    public void operation() {
        super.operation();
        this.method2();

    }

}
@SpringBootTest
class DecorateDemoApplicationTests {

    @Test
    void contextLoads() {

        Component component = new ConcreteComponent();
        component = new ConcreteDecoratorA(component);
        component = new ConcreteDecoratorB(component);
        component.operation();
    }

}

在你起初的设计中,当系统需要新功能时,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为,这种做法的问题在于,它们再主类中加入了新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的个特殊行为的需要。

而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。因此当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序的地使用装饰功能包装对象了,该设计模式符合开放封闭原则。

 源码

decorate-demo.zip-Java文档类资源-CSDN下载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

让程序飞

您的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值