Java描述设计模式(22):策略模式
2024-09-01 11:19:20
本文源码:GitHub·点这里 || GitEE·点这里
一、生活场景
每年双十一,各大电商平台会推出不同的满减策略,当用户的消费金额满一定额度后,会进行减去一定的优惠额度,从而来一波清仓甩卖,使用策略模式来描述该流程。
public class C01_InScene {
public static void main(String[] args) {
// 选择满减策略,走相应的计算方式
FullReduce strategy = new Full100 ();
Payment price = new Payment(strategy);
double quote = price.payment(300);
System.out.println("最终价格为:" + quote);
}
}
/**
* 付款
*/
class Payment {
private FullReduce fullReduce ;
public Payment (FullReduce fullReduce){
this.fullReduce = fullReduce ;
}
public double payment (double totalPrice){
return this.fullReduce.getPayMoney(totalPrice) ;
}
}
/**
* 金额满减接口
*/
interface FullReduce {
double getPayMoney (double totalPrice) ;
}
/**
* 不同的满减策略
*/
class Full100 implements FullReduce {
@Override
public double getPayMoney(double totalPrice) {
if (totalPrice >= 100){
totalPrice = totalPrice-20.0 ;
}
return totalPrice ;
}
}
class Full500 implements FullReduce {
@Override
public double getPayMoney(double totalPrice) {
if (totalPrice >= 500){
totalPrice = totalPrice-120.0 ;
}
return totalPrice ;
}
}
二、策略模式
1、基础概念
策略模式属于对象的行为模式。策略模式中定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客 户端。
2、模式图解
3、核心角色
- 环境角色
持有一个Strategy策略接口角色的引用。
- 抽象策略角色
通常由一个接口或抽象类实现。此角色给出所有的具体策略类要实现的接口。
- 具体策略角色
包装相关的算法或业务流程。
4、源码实现
public class C02_Strategy {
public static void main(String[] args) {
Strategy strategy = new ConcreteStrategyB() ;
Context context = new Context(strategy) ;
context.userMethod();
}
}
/** 环境角色类 */
class Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy 具体策略对象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
public void userMethod (){
this.strategy.strategyMethod();
}
}
/** 抽象策略类 */
interface Strategy {
// 策略方法
void strategyMethod () ;
}
/** 具体策略类 */
class ConcreteStrategyA implements Strategy {
@Override
public void strategyMethod() {
System.out.println("策略A方法");
}
}
class ConcreteStrategyB implements Strategy {
@Override
public void strategyMethod() {
System.out.println("策略B方法");
}
}
三、策略模式总结
策略模式的关键是:变化的与不变分离,体现了“对修改关闭,对扩展开放”原则。客户端增加行为不用修改原有代码,只要添加一种策略即可,易于切换、易于理解、易于扩展。策略过多是会导致类数目庞大,变得难以维护。
四、源代码地址
GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent
最新文章
- Leetcode 74 and 240. Search a 2D matrix I and II
- Javascript基础系列之(六)循环语句(do while循环)
- 安装64位版Oracle11gR2后无法启动SQLDeveloper的解决方案(原创) (2016-10-29 下午01:56)
- cocos2d-x 读取.plist文件
- 由于空间,注定的结果——第五届山东省ACM编程比赛总结
- 第九章 Criteria查询及注解
- .NET Core2.0 MVC中使用EF访问数据
- 纯CSS二级纵向菜单
- 关于SimpleDateFormat安全的时间格式化线程安全问题
- 黄聪:Windows2012-IIS8安装SSL证书
- (转)你应该知道的RPC原理
- 替罪羊树&;&;非旋treap
- CSS基础【2】:CSS常见属性
- 【MySQL】 Cannot load from mysql.proc. The table is probably corrupted
- android极光杀掉程序收不到通知
- CF960G Bandit Blues 【第一类斯特林数 + 分治NTT】
- (转)Python学习路径及练手项目合集
- springboot开篇 (一)简单邮件发送
- SpringMVC 常用注解 详解
- windows的cmd命令切换磁盘路径