标签:contain 对象 实现 one 种类 策略 bsp 并且 价格
//抽象算法类,定义所有支持的算法的公共接口。 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); ? } }
?
标签:contain 对象 实现 one 种类 策略 bsp 并且 价格
原文地址:https://www.cnblogs.com/yfy-/p/11925497.html