Strategy -- 策略模式

来源:互联网 发布:vector java 用法 编辑:程序博客网 时间:2024/06/02 23:07
  1. public interface Strategy {   
  2.   
  3.     public void operation();   
  4. }   
  5.   
  6. /**  
  7.  * 三条妙计  
  8.  */  
  9. class BackDoor implements Strategy {   
  10.   
  11.     @Override  
  12.     public void operation() {   
  13.         System.out.println("找乔国老帮忙");   
  14.     }   
  15.   
  16. }   
  17.   
  18. class GivenGreenLight implements Strategy {   
  19.   
  20.     @Override  
  21.     public void operation() {   
  22.         System.out.println("求吴国太开个绿灯");   
  23.     }   
  24.   
  25. }   
  26.   
  27. class BlockEnemy implements Strategy {   
  28.   
  29.     @Override  
  30.     public void operation() {   
  31.         System.out.println("孙夫人断后");   
  32.     }   
  33.   
  34. }   
  35.   
  36.   
  37. /**  
  38.  * 锦囊盛放妙计  
  39.  */  
  40. class Context implements Strategy{   
  41.     private Strategy mStrategy;   
  42.        
  43.     public Context(Strategy s){   
  44.         mStrategy = s;   
  45.     }   
  46.   
  47.     @Override  
  48.     public void operation() {   
  49.         mStrategy.operation();   
  50.     }   
  51.        
  52.        
  53. }  





Java代码  
  1. /**  
  2.          * 1.策略模式  
  3.          */  
  4.         System.out.println("***********1.策略模式***********");   
  5.         //生成第一个锦囊   
  6.         Context context  = new Context(new BackDoor());   
  7.         System.out.println("使用第 1 条妙计:");   
  8.         context.operation();   
  9.         //生成第二个锦囊   
  10.         context  = new Context(new GivenGreenLight());   
  11.         System.out.println("使用第 2 条妙计:");   
  12.         context.operation();   
  13.         //生成第三个锦囊   
  14.         context  = new Context(new BlockEnemy());   
  15.         System.out.println("使用第 3 条妙计:");   
  16.         context.operation();   
  17.         System.out.println("");  
原创粉丝点击