设计模式-策略模式


场景
老大:
我们的收银台项目要新增一个功能。在结账的时候,可能会打折,打几折都有可能,有的是满几百就减免多少,你来实现下这个功能。
我:
好的
我心想:
说白了,就是对总钱数进行运算得到一个新的结果。只是怎么运算的事情。不同情况下采用不同的运算方式,又可以称不同的策略。
代码如下:
策略接口
package StrategyPattern;
public interface IStrategy {
double cal(Double total);
}
打折策略
package StrategyPattern;
public class StrategyDiscount implements IStrategy {
/*
* 折扣
*/
private int discount;
public StrategyDiscount(int discount) {
this.discount = discount;
}
public double cal(Double total) {
return total * discount * 0.01;
}
}
正常无优惠
package StrategyPattern;
public class StrategyNormal implements IStrategy {
public double cal(Double total) {
return total;
}
}
返利
package StrategyPattern;
public class StrategyReturn implements IStrategy {
private double condition;
private double returnNum;
public StrategyReturn(double condition, double returnNum) {
this.condition = condition;
this.returnNum = returnNum;
}
public double cal(Double total) {
if (total >= condition)
return total - Math.floor(total / condition) * returnNum;
else
return total;
}
}
有一个context来决定使用哪个策略
package StrategyPattern;
public class StrategyContext {
private IStrategy strategy;
public StrategyContext(String type) throws Exception {
switch (type) {
case "normal":
strategy = new StrategyNormal();
break;
case "discount":
strategy = new StrategyDiscount(1);
break;
case "return":
strategy = new StrategyReturn(300, 100);
break;
default:
throw new Exception("没有合适的策略");
}
}
public double cal(Double total) {
return strategy.cal(total);
}
}
客户端直接调用 context 即可。
package StrategyPattern;
public class Program {
public static void main(String[] args) throws Exception {
String type = "打折";
double total = 100;
StrategyContext context = new StrategyContext(type);
double result = context.cal(total);
}
}
类图
客户端直接调用 StrategyContext,而其又根据不同的条件采取不同的策略。
扫码分享
版权说明
作者:SQBER
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
{0}
{5}
{1}
{2}回复
{4}
*昵称:
*邮箱:
个人站点:
*想说的话: