JAVA设计模式之策略模式

策略模式

1.什么是策略模式?

Head Frist设计模式》书中对于策略模式的定义是:定义了算法族,分别封装起来使算法之间可以相互替换,算法的变化独立于使用(调用)该算法的客户(或者叫对象)。

个人理解为定义了一系列的算法,把每个算法单独封装起来,并且他们之间可以相互替换(实现了同一个接口),使得算法可独立于使用它的客户而变化

 

2.角色

JAVA设计模式之策略模式

策略模式中包含三个角色组成(图片来源于网络):

环境类Context):应用某种决策的环境,其中有一个Strategy的引用。

决策接口类Strategy):某一类具体决策的总体抽象类,一般是一个interface类。

决策具体实现类ConcreteStrategy):实现了Strategy接口的所有方法,封装了各自的算法和行为

3.优点

1)、将代码中变化的部分单独封装起来,增加代码复用。

2)、动态的改变客户(对象)的行为。

3)、决策算法的修改不会影响调用该算法的客户(对象)的状态(注意:算法的删除会影响客户状态)。

4.缺点

1)、客户(对象)必须熟知所有的决策算法,并自行决定使用哪一种算法。

2)、算法决策类会很多。

5.使用场景

    当程序需要实现某种特定的服务或者功能,而实现的方式又不唯一时可以使用策略模式。

6.实例代码

商场销售商品每个商品都有计算价格的方法每种商品都要实现Price接口,而且每个顾客在付费结算的时候有三种价格折扣,每种折扣要实现CountStrategy接口(实例参考网络)。

 

1)、价格接口

/**

 * 价格接口

 * @date 2017年8月28日 上午9:36:01

 */

public interface Price {

/**

 * 获取价格

 * @param price

 * @auter leitao

 * @date 2017年8月28日

 */

public Double getPrice(Double price);

}


 

(2)、书本价格相关类

/**

 * 书本价格

* @date 2017年8月28日 上午9:37:24

 */

public class BookPriceimplements Price {

/**

 * 创建打折引用

 */

private CountStrategycountStrategy;

public BookPrice(CountStrategycountStrategy){

this.countStrategy=countStrategy;

}

/**

 * 计算打折过后的价格

 */

@Override

public Double getPrice(Doubleprice) {

return countStrategy.getCountPrice(price);

}

}

 

(3)、价格折扣计算接口

/**

 * 价格计算接口

* @author leitao 

* @date 2017年8月25日 下午5:25:33

 */

public interface CountStrategy {

/**

 * 获取计算过后的价格

* @return 

 */

public Double getCountPrice(Doubleprice);

}

 

(4)、初级会员折扣类

/**

 * 初级会员无折扣

* @date 2017年8月28日 上午9:41:54

 */

public class PrimaryMemberStrategyimplements CountStrategy {

@Override

public Double getCountPrice(Doubleprice) {

System.out.println("对于初级会员的没有折扣");

return price;

}

}

 

(5)、中级会员折扣类

/**

 * 中级会员折扣

* @date 2017年8月28日 上午9:41:35

 */

public class IntermediateMemberStrategyimplements CountStrategy {

@Override

public Double getCountPrice(Doubleprice) {

System.out.println("对于中级会员的折扣为10%");

return price * 0.9;

}

}

 

(6)、高级会员折扣类

/**

 * 高级会员折扣

* @date 2017年8月28日 上午9:41:13

 */

public class AdvancedMemberStrategyimplements CountStrategy {

@Override

public Double getCountPrice(Doubleprice) {

System.out.println("对于高级会员的折扣为20%");

return price * 0.8;

}

}

 

(7)、运行代码

public class Context {

public static void main(String[]args) {

//确定折扣类型

CountStrategy cs=new AdvancedMemberStrategy();

//创建书本价格对象

BookPrice bp=new BookPrice(cs);

//计算打折后的价格

Double price=bp.getPrice(36.88);

System.out.println("最终的价格是:"+price);

}

}

 

(8)、运行结果(结果精度未作处理)

 

对于高级会员的折扣为20%

最终的价格是:29.504000000000005



【乐山程序员联盟,欢迎大家加群相互交流学习5 7 1 8 1 4 7 4 3】