装饰器模式(Decorator Pattern)指在无须改变原有类及类的继承关系的情况下,动态扩展一个类的功能。它通过装饰器来包裹真实的对象,并动态地向对象添加或者撤销功能。
装饰器模式包括 Source 和 Decorator 两种角色,Source 是被装饰者,Decorator 是装饰者。
装饰器模式通过装饰器可以为被装饰者 Source 动态添加一些功能。
定义Sourceable接口:
public interface Sourceable {
public void createComputer();
}
定义Sourceable接口的实现类Source:
public class Source implements Sourceable {
@Override
public void createComputer() {
System.out.println("create computer by Source");
}
}
定义装饰器类Decorator:
public class Decorator implements Sourceable {
// 装饰者类通过构造函数将 Sourceable 实例初始化到其内部
// 并在其方法createComputer()调用原方法后加上了「装饰者逻辑」(即"make system")
private Sourceable source;
public Decorator(Sourceable source) {
this.source = source;
}
@Override
public void createComputer(){
source.createComputer();
System.out.println("make system"); // 装饰代码
}
}
测试:
public class testDemo {
public static void main(String[] args) {
// 在使用装饰者模式时,需要先定义一个待装饰的Source类的source对象
// 然后初始化构造器Decorator并在构造函数中传入source对象
// 最后调用createComputer(),程序在创建完computer后还为computer安装了系统。
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.createComputer();
}
}