策略模式浅析及应用
一、背景
程序员项目实战中,策略模式用的不可谓不多啊,必须予以重视 二、定义
Define a family of algorithms, encapsulate each one, and make them interchangeable. [The] Strategy [pattern] lets the algorithm vary independently from clients that use it. 三、目标
当然也是在实战项目中运用策略模式了啊,学会高逼格的编程技巧了啊 四、直接开撸
二哥,人狠话不多,开车…走你~~~
经典的策略代码模式:
调度上下文: public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int calculate(int a, int b) { return strategy.calculate(a, b); } }
接口定义: public interface Strategy { int calculate(int a, int b); }
算法逻辑具体实现: public class AddStrategy implements Strategy { @Override public int calculate(int a, int b) { return a + b; } } public class MulStrategy implements Strategy { @Override public int calculate(int a, int b) { return a * b; } }
调用端实现: public class ClientInvoke { public static void main(String[] args) { Strategy strategy = new AddStrategy(); Context context = new Context(strategy); System.out.println(context.calculate(10, 20)); } }
根据不同的算法策略,传入调度上下文,调度器来 调用实现。 OK,下面 来看看 实际业务场景的运用:1、日志记录功能
很多业务中需要日志记录的功能,可以实现两种日志记录的策略,数据库日志记录器、文件日志记录器。
如果数据库跪了,可以在异常处理中 做一些降级处理,哈哈哈
2、支付业务功能
针对不同的支付方式,记录不同的支付信息,或者处理不同的业务流程,等等