打字猴:1.700465467e+09
1700465467 public class ConcreteStrategy2 implements Strategy{
1700465468
1700465469 public void doSomething(){
1700465470
1700465471 System.out.println(“具体策略2的运算法则”);
1700465472
1700465473 }
1700465474
1700465475 }
1700465476
1700465477 策略模式的重点就是封装角色,它是借用了代理模式的思路,大家可以想想,它和代理模式有什么差别,差别就是策略模式的封装角色和被封装的策略类不用是同一个接口,如果是同一个接口那就成为了代理模式。我们来看封装角色,如代码清单18-9所示。
1700465478
1700465479 代码清单18-9 封装角色
1700465480
1700465481 public class Context{
1700465482
1700465483 //抽象策略
1700465484
1700465485 private Strategy strategy=null;
1700465486
1700465487 //构造函数设置具体策略
1700465488
1700465489 public Context(Strategy_strategy){
1700465490
1700465491 this.strategy=_strategy;
1700465492
1700465493 }
1700465494
1700465495 //封装后的策略方法
1700465496
1700465497 public void doAnythinig(){
1700465498
1700465499 this.strategy.doSomething();
1700465500
1700465501 }
1700465502
1700465503 }
1700465504
1700465505 高层模块的调用非常简单,知道要用哪个策略,产生出它的对象,然后放到封装角色中就完成任务了,如代码清单18-10所示。
1700465506
1700465507 代码清单18-10 高层模块
1700465508
1700465509 public class Client{
1700465510
1700465511 public static void main(String[]args){
1700465512
1700465513 //声明一个具体的策略
1700465514
1700465515 Strategy strategy=new ConcreteStrategy1();
1700465516
[ 上一页 ]  [ :1.700465467e+09 ]  [ 下一页 ]