14-策略模式
14-策略模式
1.策略模式
- 策略模式服务端。
// 订单
public class Order {
// 订单价格
private double orderPrice;
// 订单类型
private String orderType;
public Order(double orderPrice, String orderType) {
this.orderPrice = orderPrice;
this.orderType = orderType;
}
// 省略get和set方法
}
// 打折策略接口
public interface DiscountStrategy {
// 通过打折类型计算折扣价格
double calDiscount(Order order);
}
// 普通订单打折策略,不打折
public class NormalDiscountStrategy implements DiscountStrategy {
@Override
public double calDiscount(Order order) {
return 0;
}
}
// 团购订单,打九折
public class GroupDiscountStrategy implements DiscountStrategy {
@Override
public double calDiscount(Order order) {
return order.getOrderPrice() * 0.1;
}
}
// 促销订单,减去100元的促销价格
public class PromotionDiscountStrategy implements DiscountStrategy {
@Override
public double calDiscount(Order order) {
return order.getOrderPrice() - 100;
}
}
public class DiscountStrategyFactory {
private static final Map<String, DiscountStrategy> strategies = new HashMap<>();
static {
strategies.put("普通订单", new NormalDiscountStrategy());
strategies.put("团购订单", new GroupDiscountStrategy());
strategies.put("促销订单", new PromotionDiscountStrategy());
}
public static DiscountStrategy getDiscountStrategy(String orderType) {
DiscountStrategy discountStrategy;
return (discountStrategy = strategies.get(orderType)) == null ? strategies.get("普通订单") : discountStrategy;
}
}
- 策略模式客户端。
Order order = new Order(1000, "普通订单");
// 获取打折策略
DiscountStrategy discountStrategy = DiscountStrategyFactory.getDiscountStrategy(order.getOrderType());
// 通过打折策略计算折扣价格
double discount = discountStrategy.calDiscount(order);
// 订单价格 = 订单原价格 - 折扣价格
order.setOrderPrice(order.getOrderPrice() - discount);
System.out.println(order.getOrderPrice()); // 1000.0
2.策略模式总结
- <<设计模式:可复用面向对象软件的基础>>中对策略模式的定义:定义一组算法类,将每个算法分别封装,让它们可以相互替换;策略模式可以使算法的变化独立于使用它们的客户端。
- 策略模式的作用:避免冗长的if...else和switch...case语句;解耦策略的定义、创建和使用。
- 在使用策略模式消除if...else语句时,需要避免过度设计。如果if...else分支判断不重复,代码不多,就没有必要使用策略模式替换if...else,毕竟if...else是几乎所有编程语言都会提供的语法,存在即有道理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南