行为型模式-策略模式

来源:互联网 发布:软件测试模型分为 编辑:程序博客网 时间:2024/05/16 11:23

策略模式

定义一组算法,将每个算法封装起来,并且使他们之间互相联系。

其用意是定义一组算法,将每一个算法封装到具有共同接口的独立类中,从而使他们可以互相切换,使得算法在不影响到客户端的情况下发生变化。

 

策略模式角色

  1. 环境(Context)角色:该角色叫做上下文角色,起到承上启下的作用,屏蔽高层对策略、算法的直接访问,它持有一个策略的引用;
  2. 抽象策略(Strategy)角色:该角色对策略、算法进行抽象,通常定义每个策略或算法必须具备的方法和属性;
  3. 具体策略(Concrete Strategy)角色:该角色实现抽象策略中的具体操作,含有具体的算法。

策略模式的优点

  1. 策略模式提供了管理相关算法族的办法。策略类的等级结构应以了一个算法或行为族,恰当地使用继承可以把公共的代码移到父类中,从而避免代码的重复;
  2. 策略模式提供了可以替换继承关系的方法。继承可以处理多种算法或行为,如果不用策略模式,那么使用算法或行为的环境类就有可能有一些子类,每一个子类提供不同的算法或行为。但是,这样算法或行为的使用者就和算法本身混在一起,从而不可能再独立演化;
  3. 使用策略模式可以避免使用多重条件转移语句。多重条件语句不易于维护,它把采用哪一种算法或采取哪一种行为的逻辑与算法或行为的逻辑混合在一起,统统列在一个多重转移语句里面,这比继承的办法还要原始和落后。


策略模式的缺点

  1. 客户端必须知道所有的策略类,并自行决定使用哪一个策略类;
  2. 策略模式造成很多的策略类。

使用场景

  1. 多个类只是在算法或行为上稍有不同的场景;
  2. 算法需要自由切换的场景;
  3. 需要屏蔽算法规则的场景。

<span style="font-size:18px;">package strategymodel;/* * 抽象策略接口 */public interface Strategy {//计算折扣价public double discount(double price);}</span>

<span style="font-size:18px;">package strategymodel;//普通会员策略public class PlainStrategy implements Strategy {public PlainStrategy() {// TODO Auto-generated constructor stub}//普通会员无折扣价public double discount(double price) {// TODO Auto-generated method stubreturn price * 1;}}</span>

<span style="font-size:18px;">package strategymodel;//银牌会员策略public class SilverStrategy implements Strategy {public SilverStrategy() {// TODO Auto-generated constructor stub}//银牌会员折扣价public double discount(double price) {// TODO Auto-generated method stubreturn price * 0.9;}}</span>

<span style="font-size:18px;">package strategymodel;//金牌会员策略public class GoldStrategy implements Strategy {public GoldStrategy() {// TODO Auto-generated constructor stub}//金牌会员折扣价public double discount(double price) {// TODO Auto-generated method stubreturn price * 0.75;}}</span>

<span style="font-size:18px;">package strategymodel;/** * 环境角色 * */public class ContextPrice {//持有一个策略对象private Strategy strategy;public ContextPrice(Strategy strategy) {// TODO Auto-generated constructor stubthis.strategy = strategy;}//计算折扣价public double quote(double price){return strategy.discount(price);}}</span>

<span style="font-size:18px;">package strategymodel;public class Client {public static void main(String[] args) {// TODO Auto-generated method stubStrategy strategy = new PlainStrategy();ContextPrice contextPrice = new ContextPrice(strategy);System.out.println("普通会员折扣价: "+contextPrice.quote(1000.00f));strategy = new SilverStrategy();contextPrice = new ContextPrice(strategy);System.out.println("银牌会员折扣价: "+contextPrice.quote(1000.00f));strategy = new GoldStrategy();contextPrice = new ContextPrice(strategy);System.out.println("金牌会员折扣价: "+contextPrice.quote(1000.00f));}}</span>


0 0
原创粉丝点击