打字猴:1.700465713e+09
1700465713
1700465714 }
1700465715
1700465716 抽象策略定义了一个唯一的方法来执行运算。至于具体执行的是加法还是减法,运算时由上下文角色决定。我们再来看两个具体的策略,如代码清单18-15所示。
1700465717
1700465718 代码清单18-15 具体策略
1700465719
1700465720 public class Add implements Calculator{
1700465721
1700465722 //加法运算
1700465723
1700465724 public int exec(int a,int b){
1700465725
1700465726 return a+b;
1700465727
1700465728 }
1700465729
1700465730 }
1700465731
1700465732 public class Sub implements Calculator{
1700465733
1700465734 //减法运算
1700465735
1700465736 public int exec(int a,int b){
1700465737
1700465738 return a-b;
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 }
[ 上一页 ]  [ :1.700465713e+09 ]  [ 下一页 ]