装饰者模式 (Decorator Pattern) 在不改变原类文件以及不使用继承的情况下,动态地将责任附加到对象上,从而实现动态拓展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
动态的给对象添加一些额外的属性或行为。相比于使用继承,装饰者模式更加灵活。
一般来说装饰者模式有下面几个参与者:
(1) Component:装饰者和被装饰者共同的父类,是一个接口或者抽象类,用来定义基本行为。
(2) ConcreteComponent:定义具体对象,即被装饰者。
(3) Decorator:抽象装饰者,继承自 Component ,从外类来扩展 ConcreteComponent 。对于 ConcreteComponent 来说,不需要知道 Decorator 的存在,Decorator 是一个接口或抽象类
(4) ConcreteDecorator:具体装饰者,用于扩展 ConcreteComponent 。
1、抽象构件角色 Component
public interface Component {
public void sampleOperation();
}
2、具体构件角色 ConcreteComponent
public class ConcreteComponent implements Component {
@Override
public void sampleOperation() {
System.out.println("ConcreteComponent.sampleOperation()");
}
}
3、装饰角色 Decorator
public class Decorator implements Component {
Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void sampleOperation() {
// 委派给构件
component.sampleOperation();
}
}
4、具体装饰角色 ConcreteDecorator
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void sampleOperation() {
System.out.println("ConcreteDecoratorA.sampleOperation() start");
super.sampleOperation();
System.out.println("ConcreteDecoratorA.sampleOperation() end");
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void sampleOperation() {
System.out.println("ConcreteDecoratorB.sampleOperation() start");
super.sampleOperation();
System.out.println("ConcreteDecoratorB.sampleOperation() end");
}
}
5、装饰者模式的使用
public class DecoratorMain {
public static void main(String[] args) {
ConcreteComponent concreteComponent = new ConcreteComponent();
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(concreteComponent);
concreteDecoratorA.sampleOperation();
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(concreteComponent);
concreteDecoratorB.sampleOperation();
}
}
优点:装饰模式可以提供比继承更多的灵活性;通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
缺点:使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难。
本文实现源码: https://github.com/wshunli/design-patterns/tree/master/src/ch09
参考资料
1、学习、探究Java设计模式——装饰者模式 - CSDN博客
https://blog.csdn.net/a553181867/article/details/52108423
2、Java设计模式之装饰者模式(Decorator pattern) - 简书
https://www.jianshu.com/p/c26b9b4a9d9e 如果本文对您有所帮助,且您手头还很宽裕,欢迎打赏赞助我,以支付网站服务器和域名费用。
您的鼓励与支持是我更新的最大动力,我会铭记于心,倾于博客。
本文链接: https://www.wshunli.com/posts/d95b685e.html