设计模式——策略模式
策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不影响使用算法的一端。
设计一个有多种优惠活动的收银台,则会用到策略模式。
输入产品单价、产品数量,产品的优惠活动,得出总价。
对应的策略模式类图如下:
package sf.strategy; public class CashierActivityWrapper { public enum ACTIVITY_ENUM { COMMON, DISCOUNT, RETURN }; CashierActivity activity; public CashierActivityWrapper(ACTIVITY_ENUM activityEnum) { switch (activityEnum) { case DISCOUNT: activity = new CashierActivity.CashierActivityDiscount(0.8f); break; case RETURN: activity = new CashierActivity.CashierActivityReturn(300, 100); break; default: activity = new CashierActivity.CashierActivityCommon(); break; } } public float getPrice(float price, int count) { return this.activity.getPrice(price, count); } }
package sf.strategy; public abstract class CashierActivity { public abstract float getPrice(float price, int count); /** * 正常收费 */ public static class CashierActivityCommon extends CashierActivity { @Override public float getPrice(float price, int count) { return price * count; } } /** * 打折活动 */ public static class CashierActivityDiscount extends CashierActivity{ float discount; public CashierActivityDiscount(float discount) { this.discount = discount; } @Override public float getPrice(float price, int count) { return price * discount * count; } } /** * 返利活动 */ public static class CashierActivityReturn extends CashierActivity { /** * 返利条件 */ int conditionValue; /** * 返利价值 */ int returnValue; public CashierActivityReturn(int conditionValue, int returnValue) { this.conditionValue = conditionValue; this.returnValue = returnValue; } @Override public float getPrice(float price, int count) { float total = price * count; return total - ((int)(total / this.conditionValue)) * this.returnValue; } } }