c# 策略模式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Strategy
 8 {
 9     enum CardsType 
10     {
11         cards_null,
12         cards_Straight,
13         cards_Bomb,
14     }
15     abstract class Strategy 
16     {
17         abstract public CardsType Legal(List<int> list); 
18     }
19 
20     class Straight : Strategy 
21     {
22         public override CardsType Legal(List<int> list)
23         {
24             return CardsType.cards_Straight;
25         }
26     }
27 
28     class Bomb : Strategy 
29     {
30         public override CardsType Legal(List<int> list)
31         {
32             for (int i = 0; i < list.Count;++i )
33             {
34                 if (list[i]!=list[0])
35                 {
36                     return CardsType.cards_null;
37                 } 
38             }
39             return CardsType.cards_Bomb;
40         }
41     }
42 
43     class CardsList 
44     {
45         public List<int> m_list = new List<int>();
46         private Strategy m_strategy;
47 
48         public void SetStrategy(Strategy strategy) 
49         {
50             m_strategy = strategy;
51         }
52 
53         public CardsType Legal() 
54         {
55             return m_strategy.Legal(m_list);
56         }
57 
58        
59     }
60     class Program
61     {
62        
63 
64         static void Main(string[] args)
65         {
66             List<int> list1 = new List<int>();
67             List<int> list2 = new List<int>();
68             for (int i = 1; i <= 5;++i)
69             {
70                 list1.Add(i);
71             }
72             for (int i = 0; i < 4;++i )
73             {
74                 list2.Add(1);
75             }
76             CardsList list = new CardsList();
77             list.m_list.AddRange(list1);
78             list.SetStrategy(new Bomb());
79             list.SetStrategy(new Straight());
80             if ( list.Legal() == CardsType.cards_Bomb)
81             {
82                  System.Console.WriteLine("是炸弹");
83             } 
84             else if(list.Legal() == CardsType.cards_Straight)
85             {
86                 System.Console.WriteLine("是顺子");
87             }
88            
89             System.Console.ReadKey();
90         }
91     }
92 }

策略模式:针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

posted @ 2014-02-13 11:15  kadajEvo  阅读(124)  评论(0)    收藏  举报