interface IService {
public void execute();
}
public class Decorator implements IService {
private IService service;
public Decorator(IService service) {
this.service = service;
}
@Override public void execute() {
this.doSomething();
this.service.execute();
}
private void doSomething() {
System.out.println("Decorator.doSomething is running......");
}
public static void main(String[] args) {
IService service = new AnotherDecorator(new Decorator(new ServiceImpl()));
service.execute();
}
}
class AnotherDecorator implements IService {
private IService service;
public AnotherDecorator(IService service) {
this.service = service;
}
@Override public void execute() {
this.service.execute();
this.doOtherthing();
}
private void doOtherthing() {
System.out.println("AnotherDecorator.doOtherthing is running......");
}
}
输出为:
ServiceImpl is create
Decorator.doSomething is running......
ServiceImpl.service is running......
AnotherDecorator.doOtherthing is running......
* java io 流转换操作使用的是Decorator模式
* 在不影响目标类其他对象的情况下,以动态、透明的方式给单个对象添加职责。
处理那些可以撤消的职责。
* 多个Decorator和目标类必须实现的是同一个接口或者基类,必须持有接口或者基类类型的实例。
* Facade模式注重简化接口,Adapter模式注重转换接口,Bridge模式注重分离接口(抽象)与其实现,
Decorator模式注重稳定接口的前提下为对象扩展功能。