标签:策略模式 策略 res bubuko ace 模拟 9.png imp 设计
/**
* 抽象策略接口
*/
public interface IStrategy {
/**
* 定义一个计算商品价格的接口
* @param orginPrice
* @return
*/
double calPrice(double orginPrice);
}
/**
* 普通会员策略实现
* 没有优惠,按原价计算
*/
public class NormalStrategy implements IStrategy {
@Override
public double calPrice(double orginPrice) {
return orginPrice;
}
}
/**
* 黄金会员策略实现
* 按9折计价
*/
public class GoldStrategy implements IStrategy{
@Override
public double calPrice(double orginPrice) {
return orginPrice * 0.9;
}
}
/**
* Plus 会员策略实现
* Plus 按8折计价,如果折后价大于100,可以使用10块钱的优惠券
*/
public class PlusStrategy implements IStrategy {
@Override
public double calPrice(double orginPrice) {
double reamPrice = orginPrice * 0.8;
if (reamPrice > 100) {
reamPrice = reamPrice - 10;
}
return reamPrice;
}
}
/**
* 包装算法策略的使用
*/
public class Context {
private IStrategy strategy;
public IStrategy getStrategy() {
return strategy;
}
public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
}
/**
* 调用具体策略计算商品价格
* @param orginPrice
* @return
*/
public double calPrice(double orginPrice) {
return strategy.calPrice(orginPrice);
}
}
/**
* 模拟客户端调用策略
*/
public class MainTest {
public static void main(String[] args) {
IStrategy normalStrategy = new NormalStrategy();
IStrategy goldStrategy = new GoldStrategy();
IStrategy plusStrategy = new PlusStrategy();
Context context = new Context();
context.setStrategy(normalStrategy);
double result = context.calPrice(153.32);
System.out.println("normal price= " + result);
context.setStrategy(goldStrategy);
result = context.calPrice(153.32);
System.out.println("gold price= " + result);
context.setStrategy(plusStrategy);
result = context.calPrice(153.32);
System.out.println("plus price= " + result);
}
}
4、运行结果
标签:策略模式 策略 res bubuko ace 模拟 9.png imp 设计
原文地址:https://www.cnblogs.com/tspeking/p/9176709.html