概念:
  策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
     (原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.)

抽象策略角色:
       策略类,通常由一个接口或者抽象类实现。

步骤:
     (①②步比较菜,忽略。有异议者联系!)
      ①首先定义一个策略接口
      ②然后再写出你需要的实现类(这里称为“计谋”)去继承①策略接口。
      ③计谋有了,那还要有锦囊装

       /**
        * @author wonter 
        * <b>描述:</b>计谋有了,那还要有锦囊装 <br>
        * <b>邮件:</b> yiyu1@163.com <br>
        */
       public class Box {
     //①策略接口
     private IStrategy straegy;
     //向锦囊中传入计谋
     //这里类型是策略IStrategy接口,但传入的则是“实现”接口的计谋。
     public Box(IStrategy jimou){
     //改写策略
          this.straegy = jimou;
      }
     //使用计谋
     public void operate(){
          this.straegy.operate();
      }
       }

          ④使用计谋

   /**
    * @author wonter 
    * <b>描述:</b>计谋有了,那还要有锦囊装 <br>
    * <b>邮件:</b> yiyu1@163.com <br>
    */
      public class YunZhao {
    public static void main(String[] args) {
     //将锦囊声明出来
     Context context;
     System.out.println("—— 锦囊妙计一 ——");
     //向锦囊拿出**计谋
     context = new Context(new first());
      //执行计谋
     context.operate(); 
     System.out.println("—— 锦囊妙计二 ——");
     //向锦囊拿出**计谋
     context = new Context(new second());
      //执行计谋
     context.operate(); 
     System.out.println("—— 以下待为扩展 ——");
     System.out.println("——        ... ....       ——");
      }
好处:
       这就是策略模式,高内聚低耦合的特点也表现出来了。
       还有一个就是扩展性,也就是 OCP原则,只要修改 Context.java 就可以了。
       提供了一种替代继承的方法,而且既保持了继承的优点(代码重用)还比继承更灵活(算法独立,可以任意扩展)。
       避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
 /**
    * @author wonter 
    * <b>描述:</b> 一天学一个模式 更新中,请关注我的博客! <br>

    * <b>博客:</b> http://www.cnblogs.com/Javame <br>
    * <b>邮件:</b> yiyu1@163.com <br>
    */

作者: 王永wonter 发表于 2011-08-25 16:43 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"