posts - 11,comments - 13,trackbacks - 0

//以下采用函数指针的方法完成command模式
 1
#include <iostream>
 2#include <stdio.h>
 3#include  <stdlib.h>
 4
 5/*
 6command模式:将请求放入到一个类A中,将请求的操作放入另一个类B中,
 7将B作为A的一个Private成员,然后在类C中包含一个类A的Private成员,这样
 8可以通过C来完成B的处理。
 9*/

10
11class CAction
12{
13protected:
14    CAction()
15    {
16
17    }

18public:
19    ~CAction()
20    {
21
22    }

23    virtual int Operation() = 0;
24    
25}
;
26
27class CExtendAction:public CAction
28{
29public:
30    CExtendAction()
31    {
32
33    }

34    ~CExtendAction()
35    {
36
37    }

38    int Operation()
39    {
40        std::cout<<"Execute Operation!"<<std::endl;
41        return 1;
42    }

43}
;
44
45typedef int (CAction::*oper)();    //定义类成员指针
46
47class CCommand
48{
49protected:
50    CAction* _act;
51    oper    _opt;
52public:
53    CCommand(CAction* act,oper opt)
54    {
55        _act = act;
56        _opt = opt;
57    }

58
59    ~CCommand()
60    {
61
62    }

63
64    int Execute()
65    {
66        return (_act->*_opt)();
67    }

68}
;
69
70
71int main(int argc,char * argv[])
72{
73    CAction * act = new CExtendAction();
74    CCommand comd(act,&CAction::Operation);
75
76    comd.Execute();
77}
posted on 2009-06-19 10:00 Super- 阅读(282) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理