C#策略模式(Strategy Pattern)實例教程
投稿:shichen2014 字體:[增加 減小] 類型:轉載 時間:2014-09-12 我要評論
這篇文章主要介紹了C#策略模式(Strategy Pattern),以一個簡單的實例講述了C#策略模式的實現(xiàn)方法,包括策略模式的用途以及具體實現(xiàn)方法,需要的朋友可以參考下
本文以一個簡單的實例來說明C#策略模式的實現(xiàn)方法,分享給大家供大家參考。具體實現(xiàn)方法如下:
一般來說,當一個動作有多種實現(xiàn)方法,在實際使用時,需要根據(jù)不同情況選擇某個方法執(zhí)行動作,就可以考慮使用策略模式。
把動作抽象成接口,比如把玩球抽象成接口。代碼如下:
|
1
2
3
4 |
public interface IBall
{
void Play();
}
|
有可能是玩足球、籃球、排球等,把這些球類抽象成實現(xiàn)接口的類。分別如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
public class Football : IBall
{
public void Play()
{
Console.WriteLine("我喜歡足球");
}
}
public class Basketball : IBall
{
public void Play()
{
Console.WriteLine("我喜歡籃球");
}
}
public class Volleyball : IBall
{
public void Play()
{
Console.WriteLine("我喜歡排球");
}
}
|
還有一個類專門用來選擇哪種球類,并執(zhí)行接口方法:
|
1
2
3
4
5
6
7
8
9
10
11
12 |
public class SportsMan
{
private IBall ball;
public void SetHobby(IBall myBall)
{
ball = myBall;
}
public void StartPlay()
{
ball.Play();
}
}
|
客戶端需要讓用戶作出選擇,根據(jù)不同的選擇實例化具體類:
|
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 |
class Program
{
static void Main(string[] args)
{
IBall ball = null;
SportsMan man = new SportsMan();
while (true)
{
Console.WriteLine("選擇你喜歡的球類項目(1=足球, 2=籃球,3=排球)");
string input = Console.ReadLine();
switch (input)
{
case "1":
ball = new Football();
break;
case "2":
ball = new Basketball();
break;
case "3":
ball = new Volleyball();
break;
}
man.SetHobby(ball);
man.StartPlay();
}
}
}
|
程序運行結果如下圖所示:

希望本文所述對大家的C#程序設計有所幫助。
|