定義:定義一組算法,將每一個算法都封裝起來,而且使他們之間能夠互換。 html
類型:行爲類模式 算法
類圖: 編程
策略模式是對算法的封裝,把一系列的算法分別封裝到對應的類中,而且這些類實現相同的接口,相互之間能夠替換。在前面說過的行爲類模式中,有一種模式也是關注對算法的封裝——模版方法模式,對照類圖能夠看到,策略模式與模版方法模式的區別僅僅是多了一個單獨的封裝類Context,它與模版方法模式的區別在於:在模版方法模式中,調用算法的主體在抽象的父類中,而在策略模式中,調用算法的主體則是封裝到了封裝類Context中,抽象策略Strategy通常是一個接口,目的只是爲了定義規範,裏面通常不包含邏輯。其實,這只是通用實現,而在實際編程中,由於各個具體策略實現類之間不免存在一些相同的邏輯,爲了不重複的代碼,咱們經常使用抽象類來擔任Strategy的角色,在裏面封裝公共的代碼,所以,在不少應用的場景中,在策略模式中通常會看到模版方法模式的影子。 設計模式
策略模式的結構 數組
策略模式代碼實現 this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
interface
IStrategy
{
public
void
doSomething
(
)
;
}
class
ConcreteStrategy1
implements
IStrategy
{
public
void
doSomething
(
)
{
System
.
out
.
println
(
"具體策略1"
)
;
}
}
class
ConcreteStrategy2
implements
IStrategy
{
public
void
doSomething
(
)
{
System
.
out
.
println
(
"具體策略2"
)
;
}
}
class
Context
{
private
IStrategy
strategy
;
public
Context
(
IStrategy
strategy
)
{
this
.
strategy
=
strategy
;
}
public
void
execute
(
)
{
strategy
.
doSomething
(
)
;
}
}
public
class
Client
{
public
static
void
main
(
String
[
]
args
)
{
Context
context
;
System
.
out
.
println
(
"-----執行策略1-----"
)
;
context
=
new
Context
(
new
ConcreteStrategy1
(
)
)
;
context
.
execute
(
)
;
System
.
out
.
println
(
"-----執行策略2-----"
)
;
context
=
new
Context
(
new
ConcreteStrategy2
(
)
)
;
context
.
execute
(
)
;
}
}
|
策略模式的優缺點 spa
策略模式的主要優勢有: 設計
策略模式的缺點主要有兩個: code
適用場景 htm
作面向對象設計的,對策略模式必定很熟悉,由於它實質上就是面向對象中的繼承和多態,在看完策略模式的通用代碼後,我想,即便以前歷來沒有據說過策略模式,在開發過程當中也必定使用過它吧?至少在在如下兩種狀況下,你們能夠考慮使用策略模式,
策略模式是一種簡單經常使用的模式,咱們在進行開發的時候,會常常有意無心地使用它,通常來講,策略模式不會單獨使用,跟模版方法模式、工廠模式等混合使用的狀況比較多。