应用场景
拓展一个类的功能或者给一个类添加附加职责的时候需要用到
优点
1.在不改变原有对象的情况下给一个对象拓展功能
2.使用不同的组合可以实现不同的效果
3.符合开闭原则
javaapi 实现
Servlet.Api;
javax.servlet.http.HttpServletRequestWrapper
原理
装饰者模式就像拍个照 ,比如我想普通的拍个照,或者是加个滤镜,或者再加个图案,美颜等等。其用意就是不改变目标类的情况下,给目标类动态添加功能
装饰者模式的四个角色
- 抽象构件角色(Component)
- 具体构件角色(ConcreteComponent)
- 装饰角色(Decorator)
- 具体装饰角色(ConreteDecorator1、ConreteDecorator2)
代码实现
package com.hxj.designpattern.decorator;
/**
* DecoratorTest
* 拍照 添加滤镜功能 装饰者模式
*
* @author liuguang
* @date 2021/5/6 10:49
*/
public class DecoratorTest {
public static void main(String[] args) {
// Component concreteComponent = new ConcreteComponent();
//添加美颜
// Component concreteComponent = new ConreteDecorator1(new ConcreteComponent());
//添加滤镜
Component concreteComponent = new ConreteDecorator2(new ConreteDecorator1(new ConcreteComponent()));
concreteComponent.operation();
}
}
/**
* 接口
*/
interface Component {
void operation();
}
/**
* 具体实现
*/
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("拍照");
}
}
/**
* 抽象类实现
*/
abstract class Decorator implements Component {
Component component;
/**
*
* 科普一下基础知识:
* 子类继承父类,若父类存在[有参构造方法],子类也必须存在(编译器会提示,根据提示直接创建即可)
* 实例化子类,构造方法执行顺序:
* 例如:A extends B extends C; C c = new C(); 构造方法执行顺序为 A > B > C
*/
public Decorator(Component component) {
this.component = component;
}
}
/**
* 装饰类实现
*/
class ConreteDecorator1 extends Decorator {
public ConreteDecorator1(Component component) {
super(component);
}
/**
* 重写方法添加功能
*/
@Override
public void operation() {
System.out.println("添加美颜");
super.component.operation();
}
}
class ConreteDecorator2 extends Decorator {
public ConreteDecorator2(Component component) {
super(component);
}
/**
* 重写方法添加功能
*/
@Override
public void operation() {
System.out.println("添加滤镜");
super.component.operation();
}
}