小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

策略模式 C#策略模式(Strategy Pattern)實例教程

 雪柳花明 2016-09-11

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#程序設計有所幫助。

Tags:C# 策略 模式

最新評論

    

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多