定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策模式让算法独立于使用它的客户而独立变化。
角色:
- Context:环境角色,聚合抽象策略角色
- Strategy:抽象策略角色,定义策略行为
- ConcreteStrategy:具体策略角色,实现策略行为
package com.strife.pattern.strategy;
/**
* 策略模式
*
* @author mengzhenghao
* @date 2022/6/6
*/
public class StrategyCode {
public static void main(String[] args) {
// 选择满减策略,走相应的计算方式
FullReduce strategy = new Full100 ();
Payment price = new Payment(strategy);
double quote = price.payment(200);
System.out.println("最终价格为:" + quote);
}
}
/** 环境角色:Context */
class Payment {
/** 聚合抽象策略角色 */
private FullReduce fullReduce;
public Payment(FullReduce fullReduce) {
this.fullReduce = fullReduce;
}
public double payment(double totalPrice) {
return this.fullReduce.getPayMoney(totalPrice);
}
}
/** 抽象策略角色:Strategy */
interface FullReduce {
double getPayMoney (double totalPrice);
}
/** 具体策略:ConcreteStrategy */
class Full100 implements FullReduce {
@Override
public double getPayMoney(double totalPrice) {
if (totalPrice >= 100){
totalPrice = totalPrice-20.0;
}
return totalPrice;
}
}
/** 具体策略:ConcreteStrategy */
class Full500 implements FullReduce {
@Override
public double getPayMoney(double totalPrice) {
if (totalPrice >= 500){
totalPrice = totalPrice - 120.0 ;
}
return totalPrice ;
}
}