策略模式
一、定义:定义一组算法,将每个算法封装起来,并且他们可以相互替换。
二、特点:行为型模式,封装各种类型的规则,降低算法类和使用算法类之间的耦合。
//抽象算法类,定义所有支持的算法的公共接口。 public abstract class CashSuper { abstract double getResult(double price); } //具体的算法实现类,打折算法。 public class CashRebate extends CashSuper { double rebate; public CashRebate(double rebate) { this.rebate = rebate; } @Override double getResult(double price) { double result; result = price * (int) (rebate / 10); return result; } } //具体的算法实现类,返现算法。 public class CashReturn extends CashSuper { double condition = 0; double returnMoney=0; public CashReturn(double condition, double returnMoney) { this.condition = condition; this.returnMoney = returnMoney; } double getResult(double price) { double result; int w = (int) (condition / returnMoney); result = price - w * returnMoney; return result; } } //上下文 public class Context { //声明策略对象 CashSuper cashSuper; //利用简单工厂模式创建具体的cashSuper实现类 public Context(String type) throws Exception { switch (type) { case "rebate": cashSuper = new CashRebate(8); break; case "return": cashSuper = new CashReturn(500, 60); break; default: throw new Exception("没有所需的类型"); } } //利用策略模式,根据具体的策略对象来选择不同的算法。 public double ContextInterface(double price) { return cashSuper.getResult(price); } } //客户端 public class Client { public static void main(String[] args) throws Exception { double totalPrice = 1000; String type = "return"; Context context = new Context(type); totalPrice = context.ContextInterface(totalPrice); System.out.println(totalPrice); } }