设计模式之禅-策略模式

策略模式:define a family  of algorithms,encapsulate each one,and make them interchangeable.

策略模式三个角色:

  context:上下文角色,起承上启下封装作用,屏蔽高层模块对策略、算法的直接访问,封装可能存在的变化、

  strategy:抽象策略角色,策略、算法家族的抽象、接口,定义每个策略或算法必须巨涌的方法和属性。

  concreteStrategy:具体策略角色。

  

  模版:

  

 

 public interface Stategy(){

    public  void doSomething();

  }

 

 

  public class ConcreteStrategy1 implements stategy{

    public void doSomething(){

      System.out.println("具体策略1的运算法则");

    }

  }

 

  

  public class ConcreteStrategy2 implements stategy{

    public void doSomething(){

      System.out.println("具体策略2的运算法则");

    }

  }

 

  
  public class Context(){

    private Strategy strategy = null;

 

    public Context(Strategy _strategy){

      this.strategy =_strategy ;

    }

    public void doAnything(){

      this.strategy .doSomething();

    }

  }
posted @ 2012-06-10 10:55  风叉叉  阅读(126)  评论(0编辑  收藏  举报