算法族的集中管理——策略模式
策略模式是指對(duì)一系列的算法定義,并將每一個(gè)算法封裝起來(lái),而且使它們還可以相互替換。策略模式讓算法獨(dú)立于使用它的客戶而獨(dú)立變化。
我們正好可以使用策略模式加適配器模式來(lái)將查找算法的調(diào)用重新架構(gòu)。
分角色
應(yīng)用
為了學(xué)習(xí)策略模式,我們將查找算法中的BST和RedBlackBST兩個(gè)類作為研究素材,研究設(shè)計(jì)模式肯定是不能修改原有代碼,也就是說(shuō)BST和RedBlackBST不會(huì)做任何修改,在此基礎(chǔ)上,我們使用適配器模式將其封裝取出
- BSTAdapter
- RedBlackBSTAdapter
下面展示BSTAdapter的代碼,RedBlackAdapter與它相似。
package pattern.strategy;import algorithms.search.ST; import algorithms.search.STImpl.BST;public class BSTAdapter extends Strategy {@Overridepublic void algorithm() {logger.info(this.getClass().getName());ST<Integer, String> st;st = new ST<Integer, String>(new BST<Integer, String>());testST(st);}}然后貼上Strategy的代碼,省略了一些與模式無(wú)關(guān)的內(nèi)容。
public abstract class Strategy {protected static final Logger logger = LogManager.getLogger();public abstract void algorithm();// 核心抽象方法protected void testST(ST<Integer, String> sst) {...} }最后是Context的代碼
package pattern.strategy;public class Context {private Strategy strategy;public void setStrategy(Strategy strategy) {this.strategy = strategy;}public void testSTStrategy() {strategy.algorithm();} }客戶端的調(diào)用方法
package pattern.strategy;import org.junit.Test;public class StrategyClient {@Testpublic void testStrategy() {Context context = new Context();context.setStrategy(new RedBlackBSTAdapter());// 運(yùn)行時(shí)指定具體類型context.testSTStrategy();context.setStrategy(new BSTAdapter());// 運(yùn)行時(shí)指定具體類型context.testSTStrategy();} }輸出:
11:22:50[algorithm]: pattern.strategy.RedBlackBSTAdapter 11:22:50[testST]: 總耗時(shí):69ms 11:22:50[algorithm]: pattern.strategy.BSTAdapter 11:22:51[testST]: 總耗時(shí):88ms下面給出類圖
策略模式總結(jié)
缺點(diǎn):
以上展示的策略模式仍舊處于初級(jí)階段,具體算法均需要通過(guò)繼承來(lái)實(shí)現(xiàn),可以作為研究學(xué)習(xí)使用,仍然存在一些問(wèn)題,例如對(duì)具體策略類的管理,如果使用場(chǎng)景不當(dāng),可能每次都要新建一個(gè)具體策略類,因此我們這里將其與適配器模式聯(lián)用有效地避免了這一點(diǎn)。
轉(zhuǎn)載于:https://www.cnblogs.com/Evsward/p/Strategy.html
總結(jié)
以上是生活随笔為你收集整理的算法族的集中管理——策略模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 剑指offer(19)顺时针打印矩阵
- 下一篇: 初始民大-印象篇