装饰者模式(Decorator Pattern)指在无须改变原有类及类的继承关系的情况下,动态扩展一个类的功能。它通过装饰者来包裹真实的对象,并动态地向对象添加或者撤销功能。
装饰者模式包括Source和Decorator两种角色,Source是被装饰者,Decorator是装饰者。装饰者模式通过装饰者可以为被装饰者Source动态添加一些功能。UML设计图如下:
1)定义Sourceable接口:
public interface Sourceable {
public void createComputer();
}
2)定义Sourceable接口的实现类Source:
@Slf4j
public class Source implements Sourceable {
@Override
public void createComputer() {
log.info("create computer by source...");
}
}
3)定义装饰者类Decorator:
package cn.jaa.decorator_pattern;
import lombok.extern.slf4j.Slf4j;
/**
* @Author: Jaa
* @Description: 装饰者模式
* @Date 2023/11/29 23:26
*/
@Slf4j
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source) {
super();
this.source = source;
}
@Override
public void createComputer() {
source.createComputer();
// 创建完电脑后安装系统
log.info("make Win 10 system...");
}
}
4)测试装饰者模式:
package cn.jaa.decorator_pattern;
import lombok.extern.slf4j.Slf4j;
/**
* @Author: Jaa
* @Description:
* @Date 2023/11/29 23:29
*/
public class DecoratorDemoTest {
public static void main(String[] args) {
Source source = new Source();
Decorator decorator = new Decorator(source);
decorator.createComputer();
}
}
运行结果: