1. 概述
2. 代码解析
/**
* 抽象的装饰对象
*/
public abstract class ABatterCake {
protected abstract String getDesc();
protected abstract int getCost();
}
/**
* 通过组合抽象的装饰对象;
* 来调用具体的装饰对象.
*/
public class AbstractDecorator extends ABatterCake {
private ABatterCake batterCake;
public AbstractDecorator(ABatterCake batterCake) {
this.batterCake = batterCake;
}
@Override
protected String getDesc() {
return batterCake.getDesc();
}
@Override
protected int getCost() {
return batterCake.getCost();
}
}
/**
* 具体的装饰对象.
*/
public class BatterCake extends ABatterCake {
@Override
protected String getDesc() {
return "煎饼";
}
@Override
protected int getCost() {
return 8;
}
}
/**
* 具体的装饰对象
*/
public class EggDecorator extends AbstractDecorator {
public EggDecorator(ABatterCake batterCake) {
super(batterCake);
}
@Override
protected String getDesc() {
return super.getDesc() + "加蛋";
}
@Override
protected int getCost() {
return super.getCost() + 2;
}
}
/**
* 装饰者模式:
* 1. ABatterCake是抽象的装饰对象.
* 2. AbstractDecorator是抽象的装饰者; 里面组合了抽象的装饰对象;
* 3. 这样就灵活的把实际的装饰对象, 放在装饰者中.
*/
public class DecoratorTest {
public static void main(String[] args) {
ABatterCake batterCake = new BatterCake();
batterCake = new EggDecorator(batterCake);
batterCake = new EggDecorator(batterCake);
batterCake = new SausageDecorator(batterCake);
System.out.println(batterCake.getDesc() + batterCake.getCost());
}
}
3. 源码使用
- JDK中的IO操作;eg:
Reader
和BufferReader
;