package com.maom.design.D_09_Strategy;
/**
* @Title: D_09_Strategy
* @Description: 09_策略模式
* @Author maohb
* @Version 1.0
*/
public class D_09_Strategy {
public static void main(String[] args) {
double num = 200;
Context context = new Context(new StrategyB());
double newNum = context.cost(num);
System.out.println("实际付账" + newNum + "元");
}
}
/** 上下文环境 */
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
// 计算优惠后金额
public double cost(double num){
return this.strategy.cost(num);
}
}
/** 策略抽象接口 */
interface Strategy {
public double cost(double num);
}
class StrategyA implements Strategy{
public double cost(double num) {
return num * 0.8;
}
}
class StrategyB implements Strategy {
public double cost(double num) {
if(num >= 200)
return num - 50;
else
return num;
}
}
设计模式笔记_09_策略模式
最新推荐文章于 2024-09-10 17:07:09 发布