装饰器模式是在不改变原来的基础上对原有功能的增强。
类图如下:
示例代码如下:
public class PackDecorator implements IPack {
private IPack pack;
public PackDecorator(IPack pack) {
this.pack = pack;
}
@Override
public void packFruit() {
pack.packFruit();
}
}
public class CheckPackDecorator extends PackDecorator {
public CheckPackDecorator(IPack pack) {
super(pack);
check();
}
//增加功能
public void check(){
System.out.println("检查防伪----");
}
}
public class ReinForcePackDecorator extends PackDecorator {
public ReinForcePackDecorator(IPack pack) {
super(pack);
reinForce();
}
//增加加固功能
public void reinForce(){
System.out.println("打包加固-----");
}
}
public class SpeedPackDecorator extends PackDecorator {
public SpeedPackDecorator(IPack pack) {
super(pack);
addSpeed();
}
public void addSpeed(){
System.out.println("请加速-----");
}
}
public class DecoratorTest {
public static void main(String[] args) {
AbstractFactory factory = new AppleFactory();
Fruit fruit = factory.getFruit()
IPack pack = factory.getPack();
pack = new CheckPackDecorator(pack);//增加check
pack = new ReinForcePackDecorator(pack);
pack = new SpeedPackDecorator(pack);
pack.packFruit();
}
}