策略设计模式,设计模式之C++实现(二)---策略模式(Strategy)

思想本质:策略模式将具体的策略与用户隔离,用户不知道使用的具体策略,这样我们就可以根据需要灵活地替换我们的策略。
策略模式的类图如下:
}D6S6KX25(B$L7$@M%Q(BEM策略设计模式,设计模式之C++实现(二)---策略模式(Strategy)
Strategy是策略抽象类,有很多的具体策略类继承它,Context负责与用户的交互,同时可以使用不同的具体策略来配置Context。下面我们以对数组的排序
来实现并说明策略模式。
1: /* abstract strategy class******************************/
2: class Strategy
3: {
4: public:
5: virtual void Sort(int array[], int n) = 0;
6: virtual ~Strategy()
7: {
8:
9: }
10: };
11: 
12: /* SelectSortionStrategy class, Strategy's child********/
13: class SelectSortionStrategy: public Strategy
14: {
15: virtual void Sort(int array[], int n);
16: };
17: 
18: void SelectSortionStrategy::Sort(int array[], int n)
19: {
20: int tag;
21: for(int i = 0; i < n-1; i++)
22: {
23: tag = i;
24: for(int j = i+1; j < n; j++)
25: {
26: if(array[j] < array[tag])
27: {
28: tag = j;
29: }
30: }
31: 
32: int tmp;
33: tmp = array[i];
34: array[i] = array[tag];
35: array[tag] = tmp;
36: }
37: }
38: 
39: 
40: 
41: /* InsertSortionStrategy class, Strategy's child********/
42: class InsertSortionStrategy: public Strategy
43: {
44: virtual void Sort(int array[], int n);
45: };
46: 
47: void InsertSortionStrategy::Sort(int array[], int n)
48: {
49: int key;
50: for(int i = 1; i < n; i++)
51: {
52: int j;
53: key = array[i];
54: for(j = i-1; j >= 0; j--)
55: {
56: if(array[j] > key)
57: {
58: array[j+1] = array[j];
59: }
60: else
61: {
62: break;
63: }
64: }
65:
66: array[j+1] = key;
67: }
68: }
69: 
70: 
71: /* Context class****************************************/
72: class Context
73: {
74: private:
75: Strategy* m_pStrategy;
76: public:
77: Context(Strategy* pStrategy);
78: void ContextSort(int array[], int n);
79: ~Context();
80: };
81: 
82: Context::Context(Strategy* pStrategy)
83: {
84: m_pStrategy = pStrategy;
85: }
86: 
87: Context::~Context()
88: {
89: if(m_pStrategy)
90: delete m_pStrategy;
91: }
92: 
93: 
94: void Context::ContextSort(int array[], int n)
95: {
96: m_pStrategy->Sort(array, n);
97: 
98: }
Tags:  策略模式 strategy 策略设计模式

延伸阅读

最新评论

发表评论