装饰器模式
一.装饰器模式
1.1 定义
- 在不改变原类文件和使用继承的情况下,动态的扩展一个对象的功能.
- 通过创建一个包装对象(装饰),来包裹真实的对象.
二.具体实现
1.1 创建被装饰对象接口
public interface IDecorated {
void print();
}
1.2 创建被装饰对象
public class Decorated implements IDecorated{
@Override
public void print() {
System.out.println("decorated print ...");
}
}
1.3 创建装饰器抽象类
public abstract class Decorator implements IDecorated {
private IDecorated decorated;
public Decorator(IDecorated decorated){
this.decorated = decorated;
}
public void print(){
decorated.print();
}
}
1.4 创建具体装饰器
public class DecoratorA extends Decorator{
public DecoratorA(IDecorated decorated){
super(decorated);
}
@Override
public void print() {
super.print();
System.out.println("decoratorA print ...");
}
}
public class DecoratorB extends Decorator{
public DecoratorB(IDecorated decorated){
super(decorated);
}
@Override
public void print() {
super.print();
System.out.println("decoratorB print ...");
}
}
1.5 调用
public static void main(String[] args) {
IDecorated decorated = new Decorated();
Decorator decorator = new DecoratorA(decorated);
decorator.print();
decorator = new DecoratorB(new DecoratorA(decorated));
decorator.print();
}
1.6 输出
decorated print ...
decoratorA print ...
decorated print ...
decoratorA print ...
decoratorB print ...
三.优缺点
3.1 优点
- 装饰器模式和继承的共同特点就是扩展对象的功能,而装饰器模式比继承更加灵活.
- 通过使用不同的具体装饰器类,及其不同的排列组合,可以产生出大量不同的组合.
3.2 缺点
- 装饰器模式比继承更加复杂.
- 会出现一些小类,过度使用会使程序变得复杂.
四.源码
https://github.com/Seasons20/DisignPattern.git
END