设计模式2——策略模式

工厂模式是针对不同的类型创建不同的对象,当所需要的对象没有变,而只是对它们进行的操作和算法不同时,可使用策略模式。

策略模式创建不同的算法类,并返回一个基类算法对象的指针,并对它进行相关的计算或操作。

 

实例代码

Strategy.h内容

 1 #ifndef Strategy_H_H
 2 #define Strategy_H_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Oper
 8 {
 9 public:
10     Oper() {}
11     virtual int getResult(int a, int b) = 0;
12     virtual ~ Oper() {}
13 };
14 
15 class OperAdd : public Oper
16 {
17 public:
18     virtual int getResult(int a, int b) { return a+b; }
19 };
20 
21 class OperSub : public Oper
22 {
23 public:
24     virtual int getResult(int a, int b) { return a-b; }
25 };
26 
27 class Strategy
28 {
29 public:
30     Strategy(int a0, int b0) : a(a0), b(b0), oper(NULL) {}
31     int getResult(){
32         return oper->getResult(a, b);
33     }
34     void setOper(Oper *oper0){
35         oper = oper0;
36     }
37 private:
38     int a, b;
39     Oper *oper;
40 };
41 
42 void StrategyTest()
43 {
44     Strategy *strategy = new Strategy(4, 3);
45     strategy->setOper( new OperAdd() );
46     cout << strategy->getResult() << endl;
47     strategy->setOper( new OperSub() );
48     cout << strategy->getResult() << endl;
49     delete strategy;
50 }
51 
52 #endif

运行结果显而易见。

当然这里并没有考虑内存泄露等问题,使用时需要注意。若需要对其进行优化,可加入引用计数、智能指针等机制。

posted @ 2014-09-16 11:18  丛林小阁楼  阅读(180)  评论(0编辑  收藏  举报