首页 > 代码库 > 设计模式4---策略模式

设计模式4---策略模式

  商场中计算价格,经常为有很多促销方式。

     面向对象的精髓在于抽象出相同的部分已符合人类的思维方式。

  当有很多种算法可以替换(比如商品价格算法时),可以使用策略模式。

  UML图:

   Strategy为策略基类,所有商品价格的计算都是一种算法而已。

  ContextInterface用来封装具体算法,从而使客户端与价格计算分离。

  定义strtegy的interface:

  

package com.jayfulmath.designpattern.strategy;public interface ICashSuper {    public double acceptCash(double money);}

然后是各种促销的算法:

package com.jayfulmath.designpattern.strategy;public class CashSale implements ICashSuper {    private double monryrate = 1d;        public CashSale(String monryrateStr) {        this.monryrate = Double.parseDouble(monryrateStr);    }    @Override    public double acceptCash(double money) {                return monryrate*money;    }}
package com.jayfulmath.designpattern.strategy;public class CashReturn implements ICashSuper {    private double moneyCondition = 0.0d;    private double moneyReturn = 0.0d;    public CashReturn(String moneyConditionStr, String moneyReturnStr) {        try {            moneyCondition = Double.parseDouble(moneyConditionStr);            moneyReturn = Double.parseDouble(moneyReturnStr);        } catch (Exception e) {            System.out.println("parse condition wrong:" + moneyCondition                    + " moneyReturn:" + moneyReturn);        }    }    @Override    public double acceptCash(double money) {        double result = 0.0d;        if(money>=moneyCondition)        {            result = money-Math.floor(money/moneyCondition)*moneyReturn;        }        return result;    }}
package com.jayfulmath.designpattern.strategy;public class CashReturn implements ICashSuper {    private double moneyCondition = 0.0d;    private double moneyReturn = 0.0d;    public CashReturn(String moneyConditionStr, String moneyReturnStr) {        try {            moneyCondition = Double.parseDouble(moneyConditionStr);            moneyReturn = Double.parseDouble(moneyReturnStr);        } catch (Exception e) {            System.out.println("parse condition wrong:" + moneyCondition                    + " moneyReturn:" + moneyReturn);        }    }    @Override    public double acceptCash(double money) {        double result = 0.0d;        if(money>=moneyCondition)        {            result = money-Math.floor(money/moneyCondition)*moneyReturn;        }        return result;    }}
package com.jayfulmath.designpattern.strategy;public class CashNormal implements ICashSuper {    @Override    public double acceptCash(double money) {        return money;    }}

用工厂类封装的contextinterface方法:

package com.jayfulmath.designpattern.strategy;import java.text.DecimalFormat;public class CashContext {    private ICashSuper cs = null;    public CashContext(String type) {        System.out.println("商品促销活动"+type);        switch(type)        {        case "Normal":            cs = new CashNormal();            break;        case "Return 100 Reach 300":            cs = new CashReturn("300.0", "100.0");            break;        case "80%Sale":            cs = new CashSale("0.8");            break;        default:            System.out.println("没有符合的商品促销活动");            break;        }    }    public double getResult(double money) {        double result = money;        if(cs != null)        {            result =  cs.acceptCash(money);        }        String resultstr = new DecimalFormat("0.00").format(result);        result = Double.parseDouble(resultstr);                return result;            }}
package com.jayfulmath.designpattern.strategy;import java.text.DecimalFormat;public class CashContext {    private ICashSuper cs = null;    public CashContext(String type) {        System.out.println("商品促销活动"+type);        switch(type)        {        case "Normal":            cs = new CashNormal();            break;        case "Return 100 Reach 300":            cs = new CashReturn("300.0", "100.0");            break;        case "80%Sale":            cs = new CashSale("0.8");            break;        default:            System.out.println("没有符合的商品促销活动");            break;        }    }    public double getResult(double money) {        double result = money;        if(cs != null)        {            result =  cs.acceptCash(money);        }        String resultstr = new DecimalFormat("0.00").format(result);        result = Double.parseDouble(resultstr);                return result;            }}

main方法:

package com.jayfulmath.designpattern.strategy;import com.jayfulmath.designpattern.main.BasicExample;public class StrategyMain extends BasicExample {    @Override    public void startDemo() {        // TODO Auto-generated method stub        CashContext cc = null;        Commodity shoes = new Commodity("shoe", 123.5, 5);        Commodity cloths = new Commodity("cloths", 323.2, 6);        Commodity apple = new Commodity("apple", 15.62, 25);        cc = new CashContext("70%Sale");        double result = cc.getResult(shoes.getTotalPrice()                + cloths.getTotalPrice() + apple.getTotalPrice());        System.out.println("Total price is:"+result);    }}

最后是商品类:

package com.jayfulmath.designpattern.strategy;public class Commodity {		public String _name;	private double _price;	private int _count;	public double get_price() {		return _price;	}	public void set_price(double _price) {		this._price = _price;	}		public String get_name() {		return _name;	}		public void set_name(String _name) {		this._name = _name;	}		/**	 * @return the _count	 */	public int get_count() {		return _count;	}	/**	 * @param _count the _count to set	 */	public void set_count(int _count) {		this._count = _count;	}		public Commodity(String _name, double _price, int _count) {		this._name = _name;		this._price = _price;		this._count = _count;		System.out.println("买入商品"+_name+" "+_count+"个"+"单价"+_price);	}	public double getTotalPrice()	{		return _count*_price;			}}

 运行结果:

买入商品shoe 5个单价123.5买入商品cloths 6个单价323.2买入商品apple 25个单价15.62商品促销活动80%SaleTotal price is:2357.76

 策略模式的特点就是:对于各种策略(或者说算法)进行抽象封装,并且通过contextinterface工厂类来进一步封装,

 客户端只需要告诉contextinterface使用哪一个算法就可以。

设计模式4---策略模式