1700465739
1700465740
}
1700465741
1700465742
}
1700465743
1700465744
封装角色的责任是保证策略时可以相互替换,如代码清单18-15所示。
1700465745
1700465746
代码清单18-16 上下文
1700465747
1700465748
public class Context{
1700465749
1700465750
private Calculator cal=null;
1700465751
1700465752
public Context(Calculator_cal){
1700465753
1700465754
this.cal=_cal;
1700465755
1700465756
}
1700465757
1700465758
public int exec(int a,int b,String symbol){
1700465759
1700465760
return this.cal.exec(a,b);
1700465761
1700465762
}
1700465763
1700465764
}
1700465765
1700465766
代码都非常简单,该部分就不再增加注释信息了。上下文类负责把策略封装起来,具体怎么自由地切换策略则是由高层模块负责声明的,如代码清单18-17所示。
1700465767
1700465768
代码清单18-17 场景类
1700465769
1700465770
public class Client{
1700465771
1700465772
//加符号
1700465773
1700465774
public final static String ADD_SYMBOL=”+”;
1700465775
1700465776
//减符号
1700465777
1700465778
public final static String SUB_SYMBOL=”-“;
1700465779
1700465780
public static void main(String[]args){
1700465781
1700465782
//输入的两个参数是数字
1700465783
1700465784
int a=Integer.parseInt(args[0]);
1700465785
1700465786
String symbol=args[1];//符号
1700465787
1700465788
int b=Integer.parseInt(args[2]);
[
上一页 ]
[ :1.700465739e+09 ]
[
下一页 ]