Command 模式

Command 模式结合了Composite-Component模式,将Command作为Component的子类处理。UML图如下图所示
 
//main.cpp
 
#include "invoker.h"
#include "command.h"
#include "receiver.h"
void main()
{
 Receiver *rev = new Receiver();
 Command *cmd = new ConcreteCommand(rev);
 Invoker *inv = new Invoker(cmd);
 inv->Invoke();
}
 
//receiver.h
#ifndef _RECEIVER_H_
#define _RECEIVER_H_
class Receiver
{
public:
 Receiver()
 {
  cout<<"create Receiver"<
 }
 ~Receiver() {}
 virtual void Action()
 {
  cout<<"action"<
 }
};
#endif
 
//component.h
#ifndef _COMPONENT_H_
#define _COMPONENT_H_
#include
using namespace std;
class Component
{
public:
 Component()
 {
  cout<<"create Component"<
 }
 virtual void Execute()
 {
  cout<<"component execute"<
 }
 virtual ~Component(){}
};
#endif
 
//composite.h
#ifndef _COMPOSITE_H_
#define _COMPOSITE_H_
#include
#include
#include "component.h"
using namespace std;
class Composite
{
public:
 void Operation();
 void Add(Component* com);
 void Remove();
 void GetChild();
 virtual ~Composite();
protected:
 Composite()
 {
   cout<<"create composite"<< DIV>
 }
private:
 list* _com;
};
#endif

 
//composite.cpp
#include "composite.h"
 
Composite::~Composite()
{
}
void Composite::Operation()
{
 list::iterator it = _com->begin();
 for(; it != _com->end() ; it++)
  (*it)->Execute();
}
void Composite::Add(Component *com)
{
 _com->push_back(com);
}
void Composite::Remove()
{
 _com->pop_back();
}
void Composite::GetChild()
{
 
}
//command.h
#ifndef _COMMAND_H_
#define _COMMAND_H_
#include
using namespace std;
#include "component.h"
#include "receiver.h"
/***************Command:声明执行操作的接口********************/
class Command : public Component
{
public:
 virtual ~Command()
 {}
 virtual void Execute();
protected:
 Command()
 { cout<<"create command"<
};
/***************ConcreteCommand********************/
/*将一个接收者对象绑定于一个动作      */
/*调用接收者相应的操作,以实现Execute     */
/***************ConcreteCommand********************/
class ConcreteCommand : public Command
{
public:
 ConcreteCommand(Receiver* rev);
 ~ConcreteCommand()
 {}
protected:
private:
 Receiver* _rev;
};
#endif

 
//component.cpp
#include "Command.h"
void Command::Execute()
{
 
}
ConcreteCommand::ConcreteCommand(Receiver *rev)
{
 this->_rev = rev;
}
 
//invoker.h
#ifndef _INVOKER_H_
#define _INVOKER_H_
#include "Command.h"
class Invoker
{
public:
 Invoker(Command* cmd)
 {
  _cmd = cmd;
 }
 void Invoke()
 {
  cout<<"invoke"<
 }
 ~Invoker()
 {}
private:
 Command* _cmd;
};
#endif
 
输出结果为
create Receiver
create Component
create command
invoke
Press any key to continue
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值