设计模式之 Command 模式

本文详细探讨了Command设计模式,这是一种行为设计模式,用于将请求封装为一个对象,使得可以使用不同的请求、队列或者记录请求日志。内容涵盖了Command模式的基本概念、组成角色、工作原理,以及在实际开发中如何应用,如在电子邮件系统中的实现,通过将发送邮件操作抽象为Command,实现了命令的解耦和可扩展性。
摘要由CSDN通过智能技术生成
 
/********************************************************************************
* File Name     :  Command.h
*
* EMail Addr    :  seakingw@163.com
*
* Description : interface for the CCommand class.
*
********************************************************************************/

#ifndef _COMMOND_PATTERNS
#define _COMMOND_PATTERNS
#include <list>
class CCommand;
typedef std::list<CCommand *> CommandList;
typedef CommandList::iterator CommandListIt;
typedef CommandList::reverse_iterator CommandListReIt;
class CCommand
{
public:
 virtual ~CCommand();
 virtual void Execute() = 0;
 virtual void UnExecute() = 0;
protected:
 CCommand();
};
template <class Receiver>
class CSimpleCommand:public CCommand
{
public:
 typedef void (Receiver::*Action) ();
 CSimpleCommand(Receiver* r, Action a):
 _receiver(r),_action(a)
 {
 }
 virtual ~CSimpleCommand();
 virtual void Execute();
private:
 Action _action;
 Receiver* _receiver;
};
//myCloass receiver = new MyClass;
//...
//CCommand *aCommand = new CSimpleCommand<MyClass> (receiver ,&MyClass::Action);
//...
//aCommand->Execute();

class CMacroCommand :public CCommand
{
public:
 CMacroCommand();
 virtual ~CMacroCommand();
 virtual void Add(CCommand*);
 virtual void Remove(CCommand*);
 virtual void Execute();
 virtual void UnExecute();
private:
 CommandList _comds;
 
};
#endif
 
/********************************************************************************
* File Name     :  Command.cpp
*
* EMail Addr    :  seakingw@163.com
*
*
* Description : implementation of the CCommand class.
*
********************************************************************************/
#include "Command.h"
CCommand::CCommand()
{
}
CCommand::~CCommand()
{
}
template <class Receiver>
void CSimpleCommand<Receiver> ::Execute()
{
 (_receiver->*_action)();
}
template <class Receiver>
CSimpleCommand<Receiver>::~CSimpleCommand()
{
}
CMacroCommand::CMacroCommand()
{
}
CMacroCommand::~CMacroCommand()
{
}
void CMacroCommand::Execute()
{
 CommandListIt it ;
 for(it = _comds.begin(); it != _comds.end();it++)
 {
  CCommand *pCmd = *it;
  pCmd->Execute();
 }
}
void CMacroCommand::UnExecute()
{
 CommandListReIt reIt ;
 for(reIt = _comds.rbegin(); reIt != _comds.rend();reIt++)
 {
  CCommand *pCmd = *reIt;
  pCmd->UnExecute();
 }
}
void CMacroCommand::Add(CCommand*pCmd)
{
 _comds.push_back(pCmd);
}
void CMacroCommand::Remove(CCommand *pCmd)
{
 _comds.remove(pCmd);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值