【结构型模式二】装饰模式
1. 前情提要
我们在简单工厂模式实现了将计算器的加减乘除功能的实现封装起来,让客户端直接调用这些操作类的父类的运算方法,即可得到运算结果。但客户端需知道这些操作类的父类叫啥名字,才能调用它的运算功能。
客户端代码长这样:
public int computeByFactory(int num1, String operator, int num2) throws Exception {
Operation operation = OperationFactory.createOperation(operator);
return operation.operate(num1,num2);
}
在策略模式实现了使用一个策略上下文类,将调用这些操作类的父类的运算方法的过程再做封装,这样客户端连这些操作类的父类都无需知道,就可以直接通过策略上下文类调用运算方法,使得各个运算的实现和调用逻辑完全分离。
客户端代码长这样:
public int computeByStrategy(int num1, String operator, int num2) throws Exception {
return OperationContext.execute(num1,operator,num2);
}
2. 计算器又要加功能
现在如果要增加一个功能,在计算结果之前,要按指定的顺序显示出颜色。比如下面的代码,在打印结果之前,增加了按顺序打印颜色的功能。
public int computeAndShowColor(int num1, String operator, int num2) throws Exception {
showRed();
showYellow();
showYellow();
showRed();
...
showBlue();
return OperationContext.execute(num1,operator,num2);
}
private void showRed() {
System.out.println("paint red!");
System.out.println("hahaha!");
}
private void showYellow() {
System.out.println("oh!");
System.out.println("paint yellow!");
}
private void showBlu