设计模式(19):策略模式

策略模式

  • 策略模式对应与解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法。并且由客户端决定调用哪个算法。

本质

  • 分离算法,选择实现;

策略模式角色

  • 上下文类(Context): 维护了一个策略类的引用,并将客户端的请求委托给具体策略类处理;
  • 抽象策略类(Strategy): 定义了具体的算法方法;
  • 具体策略类(ConcreteStrategy): 对抽象策略类的算法具体实现;

开发中常见的场景

  • spring框架中,Resource接口,资源访问策略;
  • springmvc框架中,controller方法入参解析
  • shiro框架中,权限的认证策略;

场景

  • 某个市场人员接到单后的报价策略(CRM系统中常见问题)。报价策略很复杂,可以简单作如下分类:
    • 普通客户小批量报价
    • 普通客户大批量报价
    • 老客户小排量报价
    • 老客户大批量报价
  • 具体选用哪个报价策略,这需要根据实际情况来确定。这时候,我们采用策略模式即可。

代码实现

  • 抽象策略类(Strategy)
java 复制代码
/**
 * 抽象算法 接口
 */
public interface  Strategy {
	double getPrice(double standardPrice);
}
  • 具体策略类(ConcreteStrategy)
java 复制代码
/**
 * 新客户小批量
 */
public class NewCustomerFewStrategy implements Strategy{
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("不好意思,不打折,原件");
		return standardPrice;
	}	
}
/**
 * 新客户大批量
 */
public class newCustomermanyStrategy implements Strategy{
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("九折");
		return standardPrice*0.9;
	}	
}
/**
 * 老客户小批量
 */
public class OldCustomerFewStrategy implements Strategy{
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("八五折");
		return standardPrice*0.85;
	}	
}
/**
 * 老客户大批量
 */
public class OldCustomermanyStrategy implements Strategy{
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("七折");		
		return standardPrice*0.7;	}	
}
  • 上下文类(Context)
java 复制代码
/**
 * 负责和具体的策略类交互
 * 这样的话,具体的算法和直接的客户端调用分离了,使得算法可以独立于客户端独立的变化
 */
public class Context {
	private Strategy strategy;
	public Context(Strategy strategy) {
		this.strategy = strategy;
	}
	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}
	public void PrintPrice(double s){
		System.out.println("你该报价:"+strategy.getPrice(s));
	}	
}
  • 客户端调用
java 复制代码
public static void main(String[] args) {
	Strategy st=new OldCustomermanyStrategy();
	Context ct=new Context(st);
	ct.PrintPrice(999);
}

更多设计模式学习:

设计模式(1):介绍

设计模式(2):单例模式

设计模式(3):工厂模式

设计模式(4):建造者模式

设计模式(5):原型模式

设计模式(6):桥接模式

设计模式(7):装饰器模式

设计模式(8):组合模式

设计模式(9):外观模式

设计模式(10):享元模式

设计模式(11):适配器模式

设计模式(12):代理模式

设计模式(13):模板方法模式

设计模式(14):命令模式

设计模式(15):迭代器模式

设计模式(16):观察者模式

设计模式(17):中介者模式

设计模式(18):状态模式

设计模式持续更新中...

相关推荐
写bug写bug9 分钟前
你真的会用枚举吗
java·后端·设计模式
哆啦code梦43 分钟前
趣谈设计模式之策略模式-比特咖啡给你一杯满满的情绪价值,让您在数字世界里”畅饮“
设计模式·策略模式
华仔啊5 小时前
别学23种了!Java项目中最常用的6个设计模式,附案例
java·后端·设计模式
Keya8 小时前
MacOS端口被占用的解决方法
前端·后端·设计模式
已读不回1439 小时前
设计模式-单例模式
前端·设计模式
long3161 天前
构建者设计模式 Builder
java·后端·学习·设计模式
一乐小哥1 天前
从 JDK 到 Spring,单例模式在源码中的实战用法
后端·设计模式
付春员2 天前
23种设计模式
设计模式
Zyy~2 天前
《设计模式》工厂方法模式
设计模式·工厂方法模式
克拉克盖博2 天前
chapter03_Bean的实例化与策略模式
java·spring·策略模式