设计模式-策略模式、策略示例、策略模式对比工厂模式
1、简述
策略模式是对算法的封装,是一种行为模式,将每个算法封装到具有共同接口的独立类中,是算法本身和使用算法的客户端分离开,相互独立,从而使得他们可以相互替换
我们真实开发中会有很多这样类似的代码,这些不同的优惠方式,实际就是策略,使用策略模式就可以更优雅的实现代码
if("old".equals(discountType)){
// 老用户优惠方式
// ...
}else if("new".equals(discountType)){
// 新用户优惠方式
// ...
}else if("vip".equals(discountType)){
// 会员用户优惠方式
// ...
}else{
// 等等其他用户优惠方式
// ...
}
如上代码违背了
- 单一职责原则:一个类只有1个发生变化的原因
之后修改任何逻辑,当前方法都会被修改 - 开闭原则:对扩展开放,对修改关闭
任何的优惠方式的修改都要修改原代码,例如加入双11,618等节日优惠策略
特点
- 可以减少大量的if else语句,可自动切换不同的实现
- 扩展性强,添加策略无非就是增加一个具体的实现类而已,代价非常低
2、策略模式代码示例
public class DemoStrategy {
public static void main(String[] args) {
// 模拟客户端调用
String discountType = "old";
if("old".equals(discountType)){
// 老用户优惠策略
ConditionFactory conditionFactory = new ConditionFactory(new ConditionOldStrategy());
conditionFactory.next();
}else if("new".equals(discountType)){
// 新用户优惠策略
ConditionFactory conditionFactory = new ConditionFactory(new ConditionNewStrategy());
conditionFactory.next();
}else if("vip".equals(discountType)){
// vip客户
ConditionFactory conditionFactory = new ConditionFactory(new ConditionVipStrategy());
conditionFactory.next();
}else{
// ...
}
}
}
/**
* 策略模式接口定义
*/
interface Strategy{
// 抽象策略方法
void discountStrategy();
}
/**
* 老用户 优惠策略
*/
class ConditionOldStrategy implements Strategy{
@Override
public void discountStrategy() {
System.out.println("old discount type");
}
}
/**
* 新客 优惠策略
*/
class ConditionNewStrategy implements Strategy{
@Override
public void discountStrategy() {
System.out.println("new discount type");
}
}
/**
* vip 优惠策略
*/
class ConditionVipStrategy implements Strategy{
@Override
public void discountStrategy() {
System.out.println("vip discount type");
}
}
/**
* 策略工厂
*/
class ConditionFactory{
/**
* 持有策略引用
*/
private Strategy strategy;
/**
* 注入构造器
* @param strategy
*/
ConditionFactory(Strategy strategy){
this.strategy = strategy;
}
/**
* 调用策略的具体实现方法
*/
public void next(){
this.strategy.discountStrategy();
}
}
实际ConditionFactory对象创建过程可以定义一个枚举,在枚举类中进行绑定discountType类型
3、策略模式对比工厂模式
策略模式是一种策略一种行为,并不是一层不变的写法,主要内容:抽象策略类,具体策略
策略模式核心是如何更优雅的把这些算法组织起来,让客户端使用更便利,代码结构更清晰
虽然工厂模式与策略模式相似,工厂模式是一种创建模式
,创建具体对象,对象的具体创建和具体客户使用无关
请查看工厂模式博文