策略模式
一、介紹
??在策略模式(Strategy Pattern)中,一個(gè)類的行為或其算法可以在運(yùn)行時(shí)更改。這種類型的設(shè)計(jì)模式屬于行為型模式。
- 意圖:定義一系列的算法,把它們一個(gè)個(gè)封裝起來(lái), 并且使它們可相互替換。
- 主要解決:在有多種算法相似的情況下,使用 if...else 所帶來(lái)的復(fù)雜和難以維護(hù)。
- 何時(shí)使用:一個(gè)系統(tǒng)有許多許多類,而區(qū)分它們的只是他們直接的行為。
- 如何解決:將這些算法封裝成一個(gè)一個(gè)的類,任意地替換。
- 關(guān)鍵代碼:實(shí)現(xiàn)同一個(gè)接口。
二、優(yōu)缺點(diǎn)
2.1 優(yōu)點(diǎn)
- 算法可以自由切換。
- 避免使用多重條件判斷。
- 擴(kuò)展性良好。
2.2 缺點(diǎn)
- 策略類會(huì)增多。
- 所有策略類都需要對(duì)外暴露。
三、使用場(chǎng)景
- 如果在一個(gè)系統(tǒng)里面有許多類,它們之間的區(qū)別僅在于它們的行為,那么使用策略模式可以動(dòng)態(tài)地讓一個(gè)對(duì)象在許多行為中選擇一種行為。
- 一個(gè)系統(tǒng)需要?jiǎng)討B(tài)地在幾種算法中選擇一種。
- 如果一個(gè)對(duì)象有很多的行為,如果不用恰當(dāng)?shù)哪J?,這些行為就只好使用多重的條件選擇語(yǔ)句來(lái)實(shí)現(xiàn)。
注意事項(xiàng):如果一個(gè)系統(tǒng)的策略多于四個(gè),就需要考慮使用混合模式,解決策略類膨脹的問(wèn)題。
四、具體實(shí)現(xiàn)

1、創(chuàng)建一個(gè)接口
/**
* 策略模式接口
*
* @author zt1994 2021/4/3 17:39
*/
public interface Strategy {
/**
* 操作
*
* @param num1
* @param num2
* @return
*/
int doOperation(int num1, int num2);
}
2、創(chuàng)建實(shí)現(xiàn)接口的實(shí)體類
/**
* 加法實(shí)現(xiàn)類
*
* @author zt1994 2021/4/3 17:42
*/
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
/**
* 減法實(shí)現(xiàn)類
*
* @author zt1994 2021/4/3 17:43
*/
public class OperationSubtract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
/**
* 乘法實(shí)現(xiàn)類
*
* @author zt1994 2021/4/3 17:44
*/
public class OperationMultiply implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
3、創(chuàng)建 Context 類
/**
* context
*
* @author zt1994 2021/4/3 17:44
*/
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);
}
}
4、使用 Context 來(lái)查看當(dāng)它改變策略 Strategy 時(shí)的行為變化文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-448275.html
/**
* 策略模式測(cè)試類
*
* @author zt1994 2021/4/3 17:45
*/
public class StrategyPatternTest {
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 OperationSubtract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}
5、測(cè)試結(jié)果文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-448275.html
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
到了這里,關(guān)于策略模式(Strategy Pattern)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!