设计模式之策略模式

定义

策略模式是对算法的包装,把使用算法的责任和算法本身分隔开,委派给不同的对象管理。策略模式通常把一系列的算法包装 到一系列的策略类里面,作为一个抽象策略类的子类。

优点

1、算法可以自由切换。
2、避免使用多重条件判断。
3、扩展性良好。

缺点

1、策略类会增多。
2、所有策略类都需要对外暴露。

案例

结算价格计算,根据Vip不同等级进行运算
用户在购买商品的时候,很多时候会根据Vip等级打不同折扣,这里也基于真实电商案例来实现VIP等级价格制:

Vip0->普通价格
Vip1->减5元
Vip2->7折
Vip3->5折

实现

定义策略接口: Strategy

public interface Strategy { 
	//价格计算 
	Integer payMoney(Integer payMoney); 
}

定义Vip0策略: StrategyVipOne

@Component(value = "strategyVipOne") 
public class StrategyVipOne implements Strategy { 
	//普通会员,没有优惠 
	@Override 
	public Integer payMoney(Integer payMoney) { 
		return payMoney; 
	} 
}

定义Vip1策略: StrategyVipTwo

@Component(value = "strategyVipTwo") 
public class StrategyVipTwo implements Strategy{ 
	//策略2 
	@Override 
	public Integer payMoney(Integer payMoney) { 
		return payMoney-5; 
	} 
}

定义Vip2策略: StrategyVipThree

@Component(value = "strategyVipThree") 
public class StrategyVipThree implements Strategy{ 
	//策略3 
	@Override 
	public Integer payMoney(Integer payMoney) { 
		return (int)(payMoney*0.7); 
	} 
}

定义Vip3策略: StrategyVipFour(参照上方,省略)

定义策略工厂: StrategyFactory

@Data 
@ConfigurationProperties(prefix = "strategy") 
@Component public class StrategyFactory implements ApplicationContextAware{ 
	//ApplicationContext 
	//1、定义一个Map存储所有策略【strategyVipOne=instanceOne】 
	// 【strategyVipTwo=instanceTwo】 
	private ApplicationContext act;
	 
	//定义一个Map,存储等级和策略的关系,通过application.yml配置注入进来 
	private Map<Integer,String> strategyMap; 
	
	//3、根据会员等级获取策略【1】【2】【3】 
	public Strategy getStrategy(Integer level){ 
		//根据等级获取策略ID 
		String id = strategyMap.get(level); 
		//根据ID获取对应实例 
		return act.getBean(id,Strategy.class); 
	}
	@Override 
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
		act=applicationContext; 
	} 
}

等级策略配置:修改application.yml,将如下策略配置进去

#策略配置 
strategy: 
	strategyMap: 
		1: strategyVipOne 
		2: strategyVipTwo 
		3: strategyVipThree 
		4: strategyVipFour

可根据实际用户等级字段获取到不同的策略实现类执行payMoney

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值