什么是策略模式:
策略模式是用来封装算法的,但是在实际使用中可以用它来封装任何类型的规则。只要在分析过程中发现“需要在不同时间应用不同的业务规则”就可以考虑使用策略模式;
策略模式的优点:
策略模式简化了单元测试,因为每个算法都有自己独立的类,可以通过自己的接口单独测试;
策略模式的应用场景,以下引自百度百科:
1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
2、 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。
文章Demo借鉴《大话设计模式》
1. 商城收银系统
public double totlaPrice(double price, int num){ return price * num; }
2. 增加打折
/** * 现金收费抽象类 */ public abstract class CashSuper { public abstract double acceptCash(double price, int num); } /** * 正常收费 */ public class CashNomal extends CashSuper { @Override public double acceptCash(double price, int num) { return price * num; } } /** * 打折收费 */ public class CashRebate extends CashSuper { private double rebate = 1d; public CashRebate(double rebate) { this.rebate = rebate; } @Override public double acceptCash(double price, int num) { return price * num * rebate; } } /** * 返利收费 */ public class CashReturn extends CashSuper { //条件 private double condititon = 0.0d; //返款 private double cashReturn = 0.0d; public CashReturn(double condititon, double cashReturn) { this.condititon = condititon; this.cashReturn = cashReturn; } @Override public double acceptCash(double price, int num) { double money = price * num; if(money > condititon){ //购物满300返100 eg: 1000-1000/300*100 money = money - money/condititon*cashReturn; } return money; } }
简单工厂:
public class FactoryPattern { public static CashSuper createCashAccept(String type){ CashSuper cs = null; switch (type) { case "nomal": cs = new CashNomal(); break; case "rebate": cs = new CashRebate(0.8); break; case "return": cs = new CashReturn(300, 100); break; default: break; } return cs; } public static void main(String[] args) { CashSuper cs = createCashAccept("nomal"); double result = cs.acceptCash(80, 10); System.out.println(result); } }
策略模式:
public class StrategyPattern { CashSuper cs = null; public StrategyPattern(CashSuper cs) { this.cs = cs; } public double CashInterface(double price, int num){ return cs.acceptCash(price, num); } public static void main(String[] args) { StrategyPattern sp = new StrategyPattern(new CashNomal()); System.out.println(sp.CashInterface(80, 10)); StrategyPattern sp1 = new StrategyPattern(new CashRebate(0.8)); System.out.println(sp1.CashInterface(80, 10)); } }
策略模式+简单工厂
public class FactoryAndStrategyPattern { CashSuper cs = null; public FactoryAndStrategyPattern(String type) { switch (type) { case "nomal": this.cs = new CashNomal(); break; case "rebate": this.cs = new CashRebate(0.8); break; case "return": this.cs = new CashReturn(300, 100); break; default: break; } } public double CashInterface(double price, int num){ return cs.acceptCash(price, num); } public static void main(String[] args) { FactoryAndStrategyPattern sp = new FactoryAndStrategyPattern("nomal"); System.out.println(sp.CashInterface(80, 10)); FactoryAndStrategyPattern sp1 = new FactoryAndStrategyPattern("rebate"); System.out.println(sp1.CashInterface(80, 10)); } }