设计模式-策略模式 | Word count: 515 | Reading time: 2min | Post View:
Java 工程实践里那些“小但重要”的选择 我整理这类内容主要是为了给团队 code review 找一份对照清单。Java 生态里很多“老写法”依然能跑,但已经不是最佳实践了,新人不知道就会继续传递。这篇文章覆盖的几个点是我反复在 PR 里指出的高频问题。
设计模式-策略模式
策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换。
此模式让算法的变化独立于使用算法的客户。
在策略模式中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。主要解决在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护。
应用场景如下。
a、 一件事情,有很多方案可以实现。 b、我可以在任何时候,决定采用哪一种实现。 c.、未来可能增加更多的方案。 d、 策略模式让方案的变化不会影响到使用方案的客户。
实例:
系统的操作都要有日志记录,通常会把日志记录在数据库里面,方便后续的管理, 但是在记录日志到数据库的时候,可能会发生错误,比如暂时连不上数据库了, 那就先记录在文件里面。日志写到数据库与文件中是两种算法,但调用方不关心, 只负责写就是。
1 2 3 4 5 6 public interface Strategy { public int doOperation(int num1,int num2); }
1 2 3 4 5 6 7 public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } }
1 2 3 4 5 6 public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } }
1 2 3 4 5 6 7 public class OperationSubstract implements Strategy { @Override public int doOperation(int num1, int num2) { return num1 - num2; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 /**创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。 策略对象改变 context 对象的执行算法 */ public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1,int num2){ return strategy.doOperation(num1,num2); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
常见踩坑 code review 中反复指出的问题:用 == 比较字符串;SimpleDateFormat 作为静态字段在多线程下使用;HashMap 在多线程下使用导致死循环(JDK7)或数据丢失;Stream 上重复使用导致 IllegalStateException;时区处理混乱导致跨时区业务出错。这些都不是新问题,但每个新人都会再踩一遍。