1.装饰器模式的定义(保持接口,扩展功能)
Decorate装饰器,顾名思义,就是动态的给一个对象添加一些额外的职责,就好比对房子进行装修一样。
2.装饰器模式的特征
具有一个装饰对象。
必须拥有与被装饰对象相同的接口。
可与给被装饰对象添加额外的功能。
3.装饰器模式的典型应用,java.io包
4.装饰器模式的代码示例
/**
* @Author long
* @Date 2019/3/20 21:29
*/
public interface SourceAble { void operation();
}
/**
* @Author long
* @Date 2019/3/20 21:31
*/
public class Source implements SourceAble { @Override
public void operation() {
System.out.println("Source最原始的方法");
}
}
/**
* @Author long
* @Date 2019/3/20 21:32
*/
public class SourceDecorateA implements SourceAble { private SourceAble sourceAble; public SourceDecorateA(SourceAble sourceAble){
this.sourceAble = sourceAble;
} @Override
public void operation() {
System.out.println("SourceDecorateA before");
sourceAble.operation();
System.out.println("SourceDecorateA after");
}
}
/**
* @Author long
* @Date 2019/3/20 21:34
*/
public class SourceDecorateB implements SourceAble { private SourceAble sourceAble; public SourceDecorateB(SourceAble sourceAble){
this.sourceAble = sourceAble;
} @Override
public void operation() {
System.out.println("SourceDecorateB before");
sourceAble.operation();
System.out.println("SourceDecorateB after");
}
}
/**
* @Author long
* @Date 2019/3/20 21:48
*/
public class App { public static void main(String[] args) {
SourceAble source = new Source();
source.operation();
System.out.println("================");
SourceAble decorateA = new SourceDecorateA(source);
decorateA.operation();
System.out.println("================");
SourceAble decorateB = new SourceDecorateB(decorateA);
decorateB.operation();
}
}
Source最原始的方法
================
SourceDecorateA before
Source最原始的方法
SourceDecorateA after
================
SourceDecorateB before
SourceDecorateA before
Source最原始的方法
SourceDecorateA after
SourceDecorateB after