前言
策略模式定義了一系列算法,并將每個算法封裝起來,使它們可以互相替換,且算法的變換不會影響使用算法的客戶。
在項目開發(fā)中,我們經(jīng)常要根據(jù)不同的場景,采取不同的措施,也就是不同的策略。假設(shè)我們需要對a、b這兩個整數(shù)進(jìn)行計算,根據(jù)條件的不同,需要執(zhí)行不同的計算方式。我們可以把所有的操作都封裝在同一個函數(shù)中,然后根據(jù)if ... else ...
的形式來調(diào)用不同的計算方式,這種方式稱為硬編碼。
在實際應(yīng)用中,隨著功能和體驗的不斷增長,我們需要經(jīng)常添加/修改策略,進(jìn)而需要不斷修改已有代碼,這不僅會讓這個函數(shù)越來越難以維護(hù),還會因為修改帶來一些Bug。因此,為了解耦,我們需要使用策略模式,定義一些獨(dú)立的類來封裝不同的算法,每一個類封裝一個具體的算法。
示例代碼
策略模式的重點(diǎn)在于策略的設(shè)定,以及普通類Operator
和策略CalStrategy
的對接。通過更換實現(xiàn)同一接口的不同策略類。降低了Operator
的維護(hù)成本,解耦算法實現(xiàn)。
Go
strategy.go
文章來源:http://www.zghlxwxcb.cn/news/detail-825072.html
package strategy
// CalStrategy 是一個策略類
type CalStrategy interface {
do(int, int) int
}
// Add 為加法策略
type Add struct{}
func (*Add) do(a, b int) int {
return a + b
}
// Reduce 為減法策略
type Reduce struct{}
func (*Reduce) do(a, b int) int {
return a - b
}
// Operator 是具體的策略執(zhí)行者
type Operator struct {
strategy CalStrategy
}
// 設(shè)置策略
func (o *Operator) setStrategy(strategy CalStrategy) {
o.strategy = strategy
}
// 調(diào)用策略中的方法
func (o *Operator) calc(a, b int) int {
return o.strategy.do(a, b)
}
單元測試文章來源地址http://www.zghlxwxcb.cn/news/detail-825072.html
package strategy
import "testing"
func TestStrategy(t *testing.T) {
operator := Operator{}
operator.setStrategy(&Add{})
if operator.calc(1, 2) != 3 {
t.Fatal("Add strategy error")
}
operator.setStrategy(&Reduce{})
if operator.calc(2, 1) != 1 {
t.Fatal("Reduce strategy error")
}
}
Python
from abc import ABC, abstractmethod
class CalStrategy(ABC):
"""策略類
"""
@abstractmethod
def do(self, a: int, b: int) -> int:
pass
class Add(CalStrategy):
"""加法策略
"""
def do(self, a: int, b: int) -> int:
return a + b
class Reduce(CalStrategy):
"""減法策略
"""
def do(self, a: int, b: int) -> int:
return a - b
class Operator:
"""策略執(zhí)行者
"""
def __init__(self):
self.strategy = None
def set_strategy(self, strategy: CalStrategy):
"""設(shè)置策略
"""
self.strategy = strategy
def calc(self, a: int, b: int) -> int:
"""調(diào)用策略中的方法
"""
return self.strategy.do(a, b)
if __name__ == "__main__":
operator = Operator()
operator.set_strategy(Add())
print(operator.calc(1, 2))
operator.set_strategy(Reduce())
print(operator.calc(4, 3))
參考
- 孔令飛 - 企業(yè)級Go項目開發(fā)實戰(zhàn)
到了這里,關(guān)于[設(shè)計模式]行為型模式-策略模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!