定义,代码 摘自 《大话设计模式》
1.策略模式:定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
2.策略模式由三种角色组成:
(1)抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
(2)具体策略角色:包装了相关的算法和行为。
(3)环境角色:持有一个策略类的引用,最终给客户端调用。
abstract class Strategy {
public abstract void Algorithm();
}
public class StrategyA extends Strategy{
@Override
public void Algorithm() {
// 算法A 具体实现
System.out.println("算法A的实现");
}
}
public class StrategyB extends Strategy{
@Override
public void Algorithm() {
System.out.println("算法B");
}
}
场景类,传入你要选择的算法
public class Context {
Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void algorithm(){
strategy.Algorithm();
}
}
public class test {
public static void main(String[] args) {
Context context;
context = new Context(new StrategyA());
context.algorithm();
}
}
这种经典的策略模式,使得客户端不够简洁,理论上客户端不需要管这个对象怎么创建,只需要调用功能就好了。所以常常和简单工厂模式结合
/**
* 商场收费,利用现金,对于收银员来说,各种各样的活动和打折 对应着不同的策略
*/
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
public class CashNormal extends CashSuper{
@Override
public double acceptCash(double money) {
return money;
}
}
/**
* 打折收费
*/
public class CashRebate extends CashSuper{
private double moneyRebate = 1d;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*moneyRebate;
}
}
public class CashReturn extends CashSuper{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(double moneyCondition, double moneyReturn) {
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money;
if(money>=moneyCondition){
result = money - (money/moneyCondition)*moneyReturn;
}
return result;
}
}
package leetcode0606.DesignPatterns.Strategy._02;
/**
* 简化客户端程序,将实例化的步骤转移到 context 中
*/
public class CashContext {
private CashSuper cashSuper;
public CashContext(String type){
switch (type){
case "正常收费" :
cashSuper = new CashNormal();
break;
case "满300返100" :
cashSuper = new CashReturn(300,100);
break;
case "打八折" :
cashSuper = new CashRebate(0.8);
break;
}
}
public double getResult(double momey){
return cashSuper.acceptCash(momey);
}
}
public class test {
public static void main(String[] args) {
CashContext cashContext = new CashContext("打八折");
double result = cashContext.getResult(100);
System.out.println(result);
}
}