结构型设计模式 之 装饰器模式
2020-05-19 本文已影响0人
飞马_6886
装饰器模式是在不改变原来的基础上对原有功能的增强。
类图如下:
装饰器模式类图.jpg示例代码如下:
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();
}
}