设计模式(行为型设计模式——策略模式)
策略模式
基本定义
模式结构
代码实现
Strategy 抽象策略类
public abstract class Discount {
abstract double discountPrice(Double originalPrice);
}
ConcreteStrategy 具体策略类
public class FirstOrderDiscount extends Discount{
double discount = 0.5;
@Override
public double discountPrice(Double originalPrice) {
return originalPrice * discount;
}
}
public class MemberDiscount extends Discount{
double discount = 0.7;
@Override
public double discountPrice(Double originalPrice) {
return originalPrice * discount;
}
}
public class Top100Discount extends Discount{
double discount = 0.8;
@Override
public double discountPrice(Double originalPrice) {
return originalPrice * discount;
}
}
Context 环境类
public class Context {
public static Map<String, Discount> strategyMap = new ConcurrentHashMap<>();
static {
for (DiscountType discountType: DiscountType.values()){
try {
strategyMap.put(discountType.toString(), (Discount) Class.forName(discountType.getClassName()).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public static double discountPrice(String type, Double originalPrice){
return strategyMap.get(type).discountPrice(originalPrice);
}
public static double discountPrice(DiscountType type, Double originalPrice){
return discountPrice(type.toString(), originalPrice);
}
}
public enum DiscountType {
MEMBER("会员折扣", "com.yanyuan.gof.behavior.strategy.v2.MemberDiscount"),
FIRST_ORDER("首次下单", "com.yanyuan.gof.behavior.strategy.v2.FirstOrderDiscount"),
TOP100("前100名下单", "com.yanyuan.gof.behavior.strategy.v2.Top100Discount");
private String name;
private String className;
DiscountType(String name, String className) {
this.name = name;
this.className = className;
}
public String getName() {
return name;
}
public String getClassName() {
return className;
}
}
测试类
@Slf4j
public class Test {
public static void main(String[] args) {
Double originalPrice = 200d;
DiscountType type = DiscountType.FIRST_ORDER;
double price = Context.discountPrice(type, originalPrice);
log.info("尊敬的用户: 您所预定的游乐园门票使用 [{}] 折扣, 原价{} RMB, 折后价格 {} RMB ", type.getName(), originalPrice, price);
type = DiscountType.MEMBER;
price = Context.discountPrice(type, originalPrice);
log.info("尊敬的用户: 您所预定的游乐园门票使用 [{}] 折扣, 原价{} RMB, 折后价格 {} RMB ", type.getName(), originalPrice, price);
}
}
输出结果
优点
缺点
使用场景