JAVA中的设计模式三(策略模式)
1 package strategy;//策略模式 2 3 //抽象的行为类 4 public interface Strategy { 5 public void go();//出行方式 6 } 7 8 9 10 11 package strategy; 12 13 public class ConcreteStrategy1 implements Strategy {//具体的出行方式 14 15 @Override 16 public void go() { 17 // TODO Auto-generated method stub 18 System.out.println("坐公交车!"); 19 } 20 21 } 22 23 24 25 26 27 package strategy; 28 29 public class ConcreteStrategy2 implements Strategy {//具体的出行方式 30 31 @Override 32 public void go() { 33 // TODO Auto-generated method stub 34 System.out.println("自驾车!"); 35 } 36 }
然后创建一个调用者,也就是使用者,把能使用的行为给导入进来;
1 package strategy; 2 3 public class Context {//环境类其实也就是一个调用类,出行的人 4 private Strategy s; 5 6 public Context(Strategy s) { 7 super(); 8 this.s = s; 9 } 10 public void operate(){ 11 s.go(); 12 } 13 }
最后就是进行出行了;
1 package strategy; 2 3 public class Test { 4 public static void main(String[] args) { 5 Context c =new Context(new ConcreteStrategy1()); 6 c.operate(); 7 8 c =new Context(new ConcreteStrategy2()); 9 c.operate(); 10 } 11 }