advanced-strategy-pattern.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta name="generator" content="Asciidoctor 2.0.15">
  8. <meta name="author" content="pxzxj, pudge.zxj@gmail.com, 2021/12/6">
  9. <title>高级策略模式</title>
  10. <link rel="stylesheet" href="css/site.css">
  11. <link href="css/custom.css" rel="stylesheet">
  12. <script src="js/setup.js"></script><script defer src="js/site.js"></script>
  13. </head>
  14. <body class="article toc2 toc-left"><div id="banner-container" class="container" role="banner">
  15. <div id="banner" class="contained" role="banner">
  16. <div id="switch-theme">
  17. <input type="checkbox" id="switch-theme-checkbox" />
  18. <label for="switch-theme-checkbox">Dark Theme</label>
  19. </div>
  20. </div>
  21. </div>
  22. <div id="tocbar-container" class="container" role="navigation">
  23. <div id="tocbar" class="contained" role="navigation">
  24. <button id="toggle-toc"></button>
  25. </div>
  26. </div>
  27. <div id="main-container" class="container">
  28. <div id="main" class="contained">
  29. <div id="doc" class="doc">
  30. <div id="header">
  31. <h1>高级策略模式</h1>
  32. <div class="details">
  33. <span id="author" class="author">pxzxj</span><br>
  34. <span id="author2" class="author">pudge.zxj@gmail.com</span><br>
  35. <span id="author3" class="author">2021/12/6</span><br>
  36. </div>
  37. <div id="toc" class="toc2">
  38. <div id="toctitle">Table of Contents</div>
  39. <span id="back-to-index"><a href="index.html">Back to index</a></span><ul class="sectlevel1">
  40. <li><a href="#_背景">1. 背景</a>
  41. <ul class="sectlevel2">
  42. <li><a href="#_策略模式回顾">1.1. 策略模式回顾</a></li>
  43. <li><a href="#_策略模式的问题">1.2. 策略模式的问题</a></li>
  44. </ul>
  45. </li>
  46. <li><a href="#_实例与分析">2. 实例与分析</a>
  47. <ul class="sectlevel2">
  48. <li><a href="#_枚举实现">2.1. 枚举实现</a></li>
  49. <li><a href="#_接口代替枚举">2.2. 接口代替枚举</a></li>
  50. <li><a href="#_提取判断逻辑到接口">2.3. 提取判断逻辑到接口</a></li>
  51. <li><a href="#_缩小访问范围">2.4. 缩小访问范围</a></li>
  52. <li><a href="#_使用组合模式减少重复代码">2.5. 使用组合模式减少重复代码</a></li>
  53. <li><a href="#_自动组合">2.6. 自动组合</a></li>
  54. <li><a href="#_遍历顺序">2.7. 遍历顺序</a></li>
  55. </ul>
  56. </li>
  57. <li><a href="#_模式结构">3. 模式结构</a></li>
  58. <li><a href="#_spring中的高级策略模式">4. Spring中的高级策略模式</a></li>
  59. <li><a href="#_spring中简化的高级策略模式">5. Spring中简化的高级策略模式</a></li>
  60. </ul>
  61. </div>
  62. </div>
  63. <div id="content">
  64. <div class="sect1">
  65. <h2 id="_背景"><a class="anchor" href="#_背景"></a>1. 背景</h2>
  66. <div class="sectionbody">
  67. <div class="sect2">
  68. <h3 id="_策略模式回顾"><a class="anchor" href="#_策略模式回顾"></a>1.1. 策略模式回顾</h3>
  69. <div class="imageblock">
  70. <div class="content">
  71. <img src="images/Strategy_Pattern_in_UML.png" alt="Strategy Pattern in UML">
  72. </div>
  73. </div>
  74. <div class="paragraph">
  75. <p>策略模式是行为型设计模式的一种,UML图如上所示,<code>Context</code> 持有 <code>Strategy</code> 接口引用,实际调用时可以是 <code>ConcreteStrategyA</code> 也可以是 <code>ConcreteStrategyB</code></p>
  76. </div>
  77. <div class="paragraph">
  78. <p>策略模式与Spring Framework中的依赖注入类似,都是面向接口编程,实际使用时可以注入接口的任意实现,这种方法符合面向对象设计中的开闭原则、里氏替换原则和依赖倒转原则</p>
  79. </div>
  80. </div>
  81. <div class="sect2">
  82. <h3 id="_策略模式的问题"><a class="anchor" href="#_策略模式的问题"></a>1.2. 策略模式的问题</h3>
  83. <div class="paragraph">
  84. <p><code>Strategy</code> 有多个实现,那么 <code>Context</code> 到底该使用哪个,策略模式中一般是使用一个配置文件配置一个具体实现的全类名,这意味着将决定权交给开发者,也意味着多个 <code>Strategy</code> 的实现无法同时使用</p>
  85. </div>
  86. <div class="paragraph">
  87. <p>然而实际业务场景中我们期望根据上下文参数或者请求参数动态选择 <code>Strategy</code> 的实现处理相关业务逻辑(伪代码如下),因此考虑对策略模式进行增强,下面结合一个实例描述整个优化过程</p>
  88. </div>
  89. <div class="literalblock">
  90. <div class="content">
  91. <pre>if(conditionA) {
  92. concreteStrategyA.execute();
  93. } else (conditionB) {
  94. concreteStrategyB.execute();
  95. }</pre>
  96. </div>
  97. </div>
  98. </div>
  99. </div>
  100. </div>
  101. <div class="sect1">
  102. <h2 id="_实例与分析"><a class="anchor" href="#_实例与分析"></a>2. 实例与分析</h2>
  103. <div class="sectionbody">
  104. <div class="paragraph">
  105. <p><strong>需求</strong>: 某厂商计算开发一个二元计算器,厂商默认支持加减乘除运算,同时允许用户扩展其它运算</p>
  106. </div>
  107. <div class="admonitionblock note">
  108. <table>
  109. <tr>
  110. <td class="icon">
  111. <i class="fa icon-note" title="Note"></i>
  112. </td>
  113. <td class="content">
  114. 实际业务场景中业务逻辑会比加减乘除复杂的多,但不影响整体模式设计
  115. </td>
  116. </tr>
  117. </table>
  118. </div>
  119. <div class="sect2">
  120. <h3 id="_枚举实现"><a class="anchor" href="#_枚举实现"></a>2.1. 枚举实现</h3>
  121. <div class="paragraph">
  122. <p>加减乘除运算通常用来作为枚举抽象方法的示例如下</p>
  123. </div>
  124. <div class="listingblock">
  125. <div class="content">
  126. <pre class="highlight"><code class="language-java" data-lang="java">public enum BinaryOperation {
  127. PLUS("+") {
  128. @Override
  129. public double apply(double x, double y) {
  130. return x + y;
  131. }
  132. };
  133. // 省略减、乘、除
  134. private String symbol;
  135. BinaryOperation(String symbol) {
  136. this.symbol = symbol;
  137. }
  138. public abstract double apply(double x, double y);
  139. }
  140. </code></pre>
  141. </div>
  142. </div>
  143. <div class="paragraph">
  144. <p><strong>使用枚举能够满足默认的加减乘除运算,但显然用户无法扩展其它运算</strong></p>
  145. </div>
  146. </div>
  147. <div class="sect2">
  148. <h3 id="_接口代替枚举"><a class="anchor" href="#_接口代替枚举"></a>2.2. 接口代替枚举</h3>
  149. <div class="paragraph">
  150. <p>为了允许用户扩展,定义一个二元运算接口以及默认的加减乘除实现</p>
  151. </div>
  152. <div class="listingblock">
  153. <div class="content">
  154. <pre class="highlight"><code class="language-java" data-lang="java">public interface BinaryOperation {
  155. double apply(double x, double y);
  156. }
  157. /**
  158. * 加法实现,减乘除省略
  159. */
  160. public class PlusOperation implements BinaryOperation {
  161. @Override
  162. public double apply(double x, double y) {
  163. return x + y;
  164. }
  165. }
  166. </code></pre>
  167. </div>
  168. </div>
  169. <div class="paragraph">
  170. <p>将 <code>x</code> 、<code>y</code> 和要执行的运算封装在一个实体类 <code>CalculateRequest</code> 中并在计算器 <code>Calculator</code> 中根据不同计算类型选择 <code>BinaryOperation</code> 的不同实现</p>
  171. </div>
  172. <div class="listingblock">
  173. <div class="content">
  174. <pre class="highlight"><code class="language-java" data-lang="java">/**
  175. * 计算请求
  176. */
  177. public class CalculateRequest {
  178. private String symbol;
  179. private double x;
  180. private double y;
  181. // getter, setter
  182. }
  183. /**
  184. * 计算器
  185. */
  186. public class Calculator {
  187. private final BinaryOperation PLUS = new PlusOperation();
  188. private final BinaryOperation MINUS = new MinusOperation();
  189. private final BinaryOperation MULTIPLY = new MultiplyOperation();
  190. private final BinaryOperation DIVIDE = new DivideOperation();
  191. public double calculate(CalculateRequest calculateRequest) {
  192. String symbol = calculateRequest.getSymbol();
  193. double x = calculateRequest.getX();
  194. double y = calculateRequest.getY();
  195. if(symbol.equals("+")) {
  196. return PLUS.apply(x, y);
  197. } else if(symbol.equals("-")) {
  198. return MINUS.apply(x, y);
  199. } else if(symbol.equals("*")) {
  200. return MULTIPLY.apply(x, y);
  201. } else if(symbol.equals("/")) {
  202. return DIVIDE.apply(x, y);
  203. } else {
  204. throw new IllegalArgumentException(symbol);
  205. }
  206. }
  207. }
  208. </code></pre>
  209. </div>
  210. </div>
  211. <div class="paragraph">
  212. <p><strong>将整个判断过程都在 <code>Calculator</code> 中实现显然不是好的实践,每次新增一类运算都需要修改 <code>Calculator</code> ,这违背了面向对象设计的开闭原则,
  213. 而且该业务场景中运算是允许用户自行实现的,<code>Calculator</code> 中根本无法了解用户自行实现的运算</strong></p>
  214. </div>
  215. </div>
  216. <div class="sect2">
  217. <h3 id="_提取判断逻辑到接口"><a class="anchor" href="#_提取判断逻辑到接口"></a>2.3. 提取判断逻辑到接口</h3>
  218. <div class="paragraph">
  219. <p>针对上一节的问题可以将运算符判断的过程提取到 <code>BinaryOperation</code> 中,使用 <code>supports()</code> 方法判断是否支持特定计算请求,并重构原本的 <code>apply()</code> 方法,使用 <code>CalculateRequest</code> 作为方法参数</p>
  220. </div>
  221. <div class="listingblock">
  222. <div class="content">
  223. <pre class="highlight"><code class="language-java" data-lang="java">public interface BinaryOperation {
  224. boolean supports(CalculateRequest calculateRequest);
  225. double apply(CalculateRequest calculateRequest);
  226. }
  227. /**
  228. * 加法实现,减乘除省略
  229. */
  230. public class PlusOperation implements BinaryOperation {
  231. @Override
  232. public boolean supports(CalculateRequest calculateRequest) {
  233. return "+".equals(calculateRequest.getSymbol());
  234. }
  235. @Override
  236. public double apply(CalculateRequest calculateRequest) {
  237. return calculateRequest.getX() + calculateRequest.getY();
  238. }
  239. }
  240. </code></pre>
  241. </div>
  242. </div>
  243. <div class="paragraph">
  244. <p>在 <code>Calculator</code> 中使用一个集合保存多个 <code>BinaryOperation</code> 的实现,计算时遍历选择 <code>supports()</code> 方法返回true的实现,并提供一个 <code>addOperation()</code> 方法允许向集合中添加新的操作</p>
  245. </div>
  246. <div class="listingblock">
  247. <div class="content">
  248. <pre class="highlight"><code class="language-java" data-lang="java">public class Calculator {
  249. private final List&lt;BinaryOperation&gt; binaryOperations = new ArrayList&lt;&gt;();
  250. public Calculator() {
  251. binaryOperations.add(new PlusOperation());
  252. binaryOperations.add(new MinusOperation());
  253. binaryOperations.add(new MultiplyOperation());
  254. binaryOperations.add(new DivideOperation());
  255. }
  256. public void addOperation(BinaryOperation binaryOperation) {
  257. binaryOperations.add(binaryOperation);
  258. }
  259. public double calculate(CalculateRequest calculateRequest) {
  260. for(BinaryOperation binaryOperation : binaryOperations) {
  261. if(binaryOperation.supports(calculateRequest)) {
  262. return binaryOperation.apply(calculateRequest);
  263. }
  264. }
  265. throw new IllegalArgumentException(calculateRequest.getSymbol());
  266. }
  267. }
  268. </code></pre>
  269. </div>
  270. </div>
  271. <div class="paragraph">
  272. <p><strong>到此为止,我们的业务需求实际上已经实现了,并且 <code>BinaryOperation</code> 也已经展现了本文希望说明的高级策略模式,然而还存在优化空间</strong></p>
  273. </div>
  274. </div>
  275. <div class="sect2">
  276. <h3 id="_缩小访问范围"><a class="anchor" href="#_缩小访问范围"></a>2.4. 缩小访问范围</h3>
  277. <div class="paragraph">
  278. <p>上一节 <code>BinaryOperation</code> 的多个实现 <code>PlusOperation</code>、<code>MinusOperation</code> 都声明了 <code>public</code> ,允许所有类直接访问,实际上这是没必要的,
  279. 不符合权限最小化的原则,jdk 1.8提供的接口静态方法可以对此进行优化,将 <code>PlusOperation</code>、<code>MinusOperation</code> 都改为默认包级别的访问,
  280. 并在 <code>BinaryOperation</code> 接口中提供静态方法返回对应运算的实例</p>
  281. </div>
  282. <div class="listingblock">
  283. <div class="content">
  284. <pre class="highlight"><code class="language-java" data-lang="java">class PlusOperation implements BinaryOperation {
  285. //...
  286. }
  287. public interface BinaryOperation {
  288. boolean supports(CalculateRequest calculateRequest);
  289. double apply(CalculateRequest calculateRequest);
  290. static BinaryOperation plusOperation() {
  291. return new PlusOperation();
  292. }
  293. // 减乘除省略
  294. }
  295. public class Calculator {
  296. private final List&lt;BinaryOperation&gt; binaryOperations = new ArrayList&lt;&gt;();
  297. public Calculator() {
  298. binaryOperations.add(BinaryOperation.plusOperation());
  299. binaryOperations.add(BinaryOperation.minusOperation());
  300. binaryOperations.add(BinaryOperation.miltiplyOperation());
  301. binaryOperations.add(BinaryOperation.divideOperation());
  302. }
  303. //...
  304. }
  305. </code></pre>
  306. </div>
  307. </div>
  308. </div>
  309. <div class="sect2">
  310. <h3 id="_使用组合模式减少重复代码"><a class="anchor" href="#_使用组合模式减少重复代码"></a>2.5. 使用组合模式减少重复代码</h3>
  311. <div class="paragraph">
  312. <p>本示例使用 <code>Calculator</code> 封装了多个 <code>BinaryOperator</code> 实现各类型运算,那么如果有另一个客户端类也希望使用 <code>BinaryOperator</code> 及其实现呢,它也需要使用一个集合属性添加所有 <code>BinaryOperator</code> 的实现,使用时不断遍历选择一个实现</p>
  313. </div>
  314. <div class="paragraph">
  315. <p>显然,添加默认实现以及遍历选择的代码都属于重复代码可以再次进行封装,一种方式是将它们封装在一个工具类中,然后更好的是使用组合模式</p>
  316. </div>
  317. <div class="listingblock">
  318. <div class="content">
  319. <pre class="highlight"><code class="language-java" data-lang="java">public class CompositeBinaryOperation implements BinaryOperation {
  320. private Collection&lt;BinaryOperation&gt; binaryOperations;
  321. public CompositeBinaryOperation() {
  322. binaryOperations = new ArrayList&lt;&gt;();
  323. binaryOperations.add(BinaryOperation.plusOperation());
  324. binaryOperations.add(BinaryOperation.minusOperation());
  325. binaryOperations.add(BinaryOperation.multiplyOperation());
  326. binaryOperations.add(BinaryOperation.divideOperation());
  327. }
  328. public void addOperation(BinaryOperation binaryOperation) {
  329. binaryOperations.add(binaryOperation);
  330. }
  331. @Override
  332. public boolean supports(CalculateRequest calculateRequest) {
  333. return binaryOperations.stream().anyMatch(op -&gt; op.supports(calculateRequest));
  334. }
  335. @Override
  336. public double apply(CalculateRequest calculateRequest) {
  337. return binaryOperations.stream()
  338. .filter(op -&gt; op.supports(calculateRequest))
  339. .findFirst()
  340. .orElseThrow(IllegalArgumentException::new)
  341. .apply(calculateRequest);
  342. }
  343. }
  344. </code></pre>
  345. </div>
  346. </div>
  347. <div class="paragraph">
  348. <p>客户端代码中可以直接使用 <code>new</code> 创建 <code>CompositeBinaryOperation</code> ,不过更好的方式是结合Spring Framework使用,
  349. 将 <code>CompositeBinaryOperation</code> 声明为一个Bean注入到客户端代码中,这样做的好处是客户端代码仍然可以面向接口 <code>BinaryOperation</code> 开发,遵循里氏代换原则和依赖倒转原则</p>
  350. </div>
  351. <div class="listingblock">
  352. <div class="content">
  353. <pre class="highlight"><code class="language-java" data-lang="java">@Configuration
  354. public class OperationConfig {
  355. @Bean
  356. public BinaryOperation compositeBinaryOperation() {
  357. CompositeBinaryOperation compositeBinaryOperation = new CompositeBinaryOperation();
  358. //添加其它运算符
  359. compositeBinaryOperation.addOperation(new CustomOperation());
  360. return compositeBinaryOperation;
  361. }
  362. }
  363. @Service
  364. class Calculator {
  365. private final BinaryOperation binaryOperation;
  366. public Calculator(BinaryOperation binaryOperation) {
  367. this.binaryOperation = binaryOperation;
  368. }
  369. public double calculate(CalculateRequest calculateRequest) throws OperationNotSupportedException {
  370. return binaryOperation.apply(calculateRequest);
  371. }
  372. }
  373. </code></pre>
  374. </div>
  375. </div>
  376. </div>
  377. <div class="sect2">
  378. <h3 id="_自动组合"><a class="anchor" href="#_自动组合"></a>2.6. 自动组合</h3>
  379. <div class="paragraph">
  380. <p>上一节使用组合模式时手动为每一个实现类创建实例并添加到 <code>CompositeBinaryOperation</code> 中,更好的方式是使用Spring的自动注入功能自动将所有实现类的实例添加到 <code>CompositeBinaryOperation</code> 中,后续新增其它实现时只需要添加其对应的Bean即可,这样更加符合 <code>面向新增开放面向修改关闭</code> 的原则,要注意的是此时Spring容器中存在多个 <code>BinaryOperation</code> 类型的Bean,因此在 <code>compositeBinaryOperation</code> 上添加 <code>@Primary</code> 注解表示自动装配时优先使用它</p>
  381. </div>
  382. <div class="listingblock">
  383. <div class="content">
  384. <pre class="highlight"><code class="language-java" data-lang="java">@Configuration
  385. public class OperationConfig {
  386. @Bean
  387. public BinaryOperation plusOperation(){
  388. return new PlusOperation();
  389. }
  390. @Bean
  391. public BinaryOperation minusOperation(){
  392. return new MinusOperation();
  393. }
  394. @Bean
  395. @Primary
  396. public BinaryOperation compositeBinaryOperation(List&lt;BinaryOperation&gt; binaryOperations) {
  397. return new CompositeBinaryOperation(binaryOperations);
  398. }
  399. }
  400. </code></pre>
  401. </div>
  402. </div>
  403. </div>
  404. <div class="sect2">
  405. <h3 id="_遍历顺序"><a class="anchor" href="#_遍历顺序"></a>2.7. 遍历顺序</h3>
  406. <div class="paragraph">
  407. <p>上面几节使用集合保存了多个 <code>BinaryOperation</code> 的实现使用时进行遍历,某些场景下还需要控制遍历顺序,此时考虑 <code>BinaryOperation</code> 继承Spring Framework提供的 <code>Ordered</code> 接口,遍历时按照不同实现的顺序进行遍历</p>
  408. </div>
  409. <div class="listingblock">
  410. <div class="content">
  411. <pre class="highlight"><code class="language-java" data-lang="java">public interface BinaryOperation extends Ordered {
  412. boolean supports(CalculateRequest calculateRequest);
  413. double apply(CalculateRequest calculateRequest);
  414. }
  415. </code></pre>
  416. </div>
  417. </div>
  418. </div>
  419. </div>
  420. </div>
  421. <div class="sect1">
  422. <h2 id="_模式结构"><a class="anchor" href="#_模式结构"></a>3. 模式结构</h2>
  423. <div class="sectionbody">
  424. <div class="paragraph">
  425. <p>通过上面的示例可以总结高级策略模式主要是在原有策略模式接口上新增一个 <code>supports()</code> 方法,接口的实现类在 <code>supports()</code> 方法中添加判断逻辑,<code>supports()</code> 方法返回true时表示此实现可以处理当前请求</p>
  426. </div>
  427. <div class="paragraph">
  428. <p>上下文类 <code>Context</code> 以集合或者组合模式的方式持有多个策略接口的实现,执行业务操作时选择 <code>supports()</code> 方法返回true的实现</p>
  429. </div>
  430. <div class="imageblock">
  431. <div class="content">
  432. <img src="images/advanced-strategy-pattern.png" alt="advanced strategy pattern">
  433. </div>
  434. </div>
  435. </div>
  436. </div>
  437. <div class="sect1">
  438. <h2 id="_spring中的高级策略模式"><a class="anchor" href="#_spring中的高级策略模式"></a>4. Spring中的高级策略模式</h2>
  439. <div class="sectionbody">
  440. <div class="paragraph">
  441. <p>Spring中也大量使用了高级策略模式,例如</p>
  442. </div>
  443. <div class="exampleblock">
  444. <div class="title">Example 1. org.springframework.validation.Validator</div>
  445. <div class="content">
  446. <div class="listingblock">
  447. <div class="content">
  448. <pre class="highlight"><code class="language-java" data-lang="java">public interface Validator {
  449. boolean supports(Class&lt;?&gt; clazz);
  450. void validate(Object target, Errors errors);
  451. }
  452. </code></pre>
  453. </div>
  454. </div>
  455. </div>
  456. </div>
  457. <div class="exampleblock">
  458. <div class="title">Example 2. org.springframework.web.method.support.HandlerMethodArgumentResolver</div>
  459. <div class="content">
  460. <div class="listingblock">
  461. <div class="content">
  462. <pre class="highlight"><code class="language-java" data-lang="java">public interface HandlerMethodArgumentResolver {
  463. boolean supportsParameter(MethodParameter parameter);
  464. @Nullable
  465. Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
  466. NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception;
  467. }
  468. </code></pre>
  469. </div>
  470. </div>
  471. </div>
  472. </div>
  473. </div>
  474. </div>
  475. <div class="sect1">
  476. <h2 id="_spring中简化的高级策略模式"><a class="anchor" href="#_spring中简化的高级策略模式"></a>5. Spring中简化的高级策略模式</h2>
  477. <div class="sectionbody">
  478. <div class="paragraph">
  479. <p><code>execute()</code> 方法有返回值时,可以使用它的返回值判断来代替 <code>supports()</code> 方法,典型的示例是SpringMVC中的 <code>org.springframework.web.servlet.HandlerMapping</code></p>
  480. </div>
  481. <div class="listingblock">
  482. <div class="content">
  483. <pre class="highlight"><code class="language-java" data-lang="java">package org.springframework.web.servlet;
  484. public interface HandlerMapping {
  485. /**
  486. * Returns null if no match was found. This is not an error. The DispatcherServlet will query all registered HandlerMapping beans to find a match, and only decide there is an error if none can find a handler.
  487. * @param request - current HTTP request
  488. * @return a HandlerExecutionChain instance containing handler object and any interceptors, or null if no mapping found
  489. * @throws Exception - if there is an internal error
  490. */
  491. @Nullable
  492. HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception; <i class="conum" data-value="1"></i><b>(1)</b>
  493. }
  494. </code></pre>
  495. </div>
  496. </div>
  497. <div class="olist arabic">
  498. <ol class="arabic">
  499. <li>
  500. <p>注意方法添加了 <code>@Nullable</code> 注解表示它的返回值可能是null,并且在注释中说明了null返回值的意义,这些不是必须的,但却是最佳实践</p>
  501. </li>
  502. </ol>
  503. </div>
  504. <div class="paragraph">
  505. <p><code>HandlerMapping</code> 的调用者需要判断 <code>getHandler</code> 的返回值,非空则返回</p>
  506. </div>
  507. <div class="listingblock">
  508. <div class="content">
  509. <pre class="highlight"><code class="language-java" data-lang="java">package org.springframework.web.servlet;
  510. public class DispatcherServlet extends FrameworkServlet {
  511. @Nullable
  512. private List&lt;HandlerMapping&gt; handlerMappings;
  513. @Nullable
  514. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
  515. if (this.handlerMappings != null) {
  516. for (HandlerMapping mapping : this.handlerMappings) {
  517. HandlerExecutionChain handler = mapping.getHandler(request);
  518. if (handler != null) {
  519. return handler;
  520. }
  521. }
  522. }
  523. return null;
  524. }
  525. }
  526. </code></pre>
  527. </div>
  528. </div>
  529. </div>
  530. </div>
  531. </div>
  532. <div id="footer">
  533. <div id="footer-text">
  534. Last updated 2024-03-18 05:44:42 UTC
  535. </div>
  536. </div>
  537. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.3/highlight.min.js"></script>
  538. <script>
  539. if (!hljs.initHighlighting.called) {
  540. hljs.initHighlighting.called = true
  541. ;[].slice.call(document.querySelectorAll('pre.highlight > code')).forEach(function (el) { hljs.highlightBlock(el) })
  542. }
  543. </script>
  544. <script src="https://utteranc.es/client.js"
  545. repo="pxzxj/articles"
  546. issue-term="title"
  547. label="utteranc"
  548. theme="github-light"
  549. crossorigin="anonymous"
  550. async>
  551. </script>
  552. </div>
  553. </div>
  554. </div>
  555. </body>
  556. </html>