前段時間看到某人《關於某道C#上機題的OO》 ,後來又有人用了裝飾模式做這題,我這裡來個策略模式,不習慣廢話直接上代碼,不知道算不算策略模式,請高人指點。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 namespace ConsoleApp
5 {
6 public class Program
7 {
8 static void Main(string[] args)
9 {
10 Game game = new Game(17);
11 //設定策略
12 game.Strategy = new StrategyA();
13 game.GameOver += new EventHandler(game_GameOver);
14 game.Start();
15 Console.Read();
16 }
17 static void game_GameOver(object sender, EventArgs e)
18 {
19 Console.WriteLine("Last Person:" + sender);
20 }
21 }
22 /// <summary>
23 /// 策略接口
24 /// </summary>
25 public interface IStrategy
26 {
27 /// <summary>
28 /// 運行策略
29 /// </summary>
30 /// <param name="g"></param>
31 void Work(Game g);
32 }
33 /// <summary>
34 /// 策略A
35 /// 從第一個人開始報數,報到3的倍數退出,一直到剩下最後一個人,用面向對象的思想去做這道題。
36 /// </summary>
37 public class StrategyA : IStrategy
38 {
39 private List<Person> over = new List<Person>();
40 private int k = 0;
41 public void Work(Game game)
42 {
43 foreach (Person p in game.Players)
44 {
45 p.Say(++k);
46 if (k % 3 == 0)
47 over.Add(p);
48 }
49 game.Players.RemoveAll(o => over.Contains(o));
50 }
51 }
52 public delegate void EventHandler(object sender , EventArgs e);
53 /// <summary>
54 /// 游戲
55 /// </summary>
56 public class Game
57 {
58 public Game(int num)
59 {
60 Players = new List<Person>();
61 for (int i = 0; i < num; i++) {
62 Players.Add(new Person(i + 1));
63 }
64 }
65 /// <summary>
66 /// 游戲策略
67 /// </summary>
68 public IStrategy Strategy { get; set; }
69 /// <summary>
70 /// 游戲玩家
71 /// </summary>
72 public List<Person> Players { get; set; }
73 /// <summary>
74 /// 游戲結束事件
75 /// </summary>
76 public event EventHandler GameOver;
77 /// <summary>
78 /// 開始游戲
79 /// </summary>
80 public void Start()
81 {
82 if (Strategy != null)
83 {
84 while (Players.Count > 1)
85 {
86 Strategy.Work(this);
87 }
88 GameOver(this.Players.First().Id, new EventArgs());
89 }
90 }
91 }
92 /// <summary>
93 /// 玩家
94 /// </summary>
95 public class Person
96 {
97 public Person(int id)
98 {
99 this.Id = id;
100 }
101 /// <summary>
102 /// 玩家ID
103 /// </summary>
104 public int Id { get; set; }
105 /// <summary>
106 /// 玩家報數
107 /// </summary>
108 /// <param name="num"></param>
109 public void Say(int num)
110 {
111 Console.WriteLine(string.Format("{0}:{1}", Id, num));
112 }
113 }
114 }
115
StrategyA 實現接口 IStrategy 遵循開閉原則,如果我們要換一個規則只要添加一個類實現IStrategy即可。
之前還有用 循環鏈表 來完成這道題,晚上再發上來。