一个消息可能会进行多种处理,把各种handle抽象出来,在我们需要某种handle的时候,将其加入到handle group进行集中处理
#include <iostream>
#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
typedef std::string Message;
class MessageHandle
{
public:
virtual void handle(Message& msg) = 0;
virtual ~MessageHandle() { }
};
class Encrypt : public MessageHandle
{
public:
virtual void handle(Message& msg)
{
std::cout << "encrypt:" << msg << std::endl;
}
};
class Decrypt : public MessageHandle
{
public:
virtual void handle(Message& msg)
{
std::cout << "decrypt:" << msg << std::endl;
}
};
class Compress : public MessageHandle
{
public:
virtual void handle(Message& msg)
{
std::cout << "compress:" << msg << std::endl;
}
};
class Decompress : public MessageHandle
{
public:
virtual void handle(Message& msg)
{
std::cout << "decompress:" << msg << std::endl;
}
};
typedef boost::shared_ptr<MessageHandle> MessageHandlePtr;
class MessageHandleGroup
{
public:
void add(MessageHandlePtr messageHandlePtr)
{
messageHandlePtrGroup_.push_back(messageHandlePtr);
}
void execute(Message &msg)
{
std::vector<MessageHandlePtr>::iterator iter =
messageHandlePtrGroup_.begin();
for (; iter!=messageHandlePtrGroup_.end(); ++iter)
{
(*iter)->handle(msg);
}
}
private:
std::vector<MessageHandlePtr> messageHandlePtrGroup_;
};
int main(void)
{
Message msg("hello, world!");
MessageHandleGroup messageHandleGroup;
messageHandleGroup.add(MessageHandlePtr(new Encrypt()));
messageHandleGroup.add(MessageHandlePtr(new Decrypt()));
messageHandleGroup.add(MessageHandlePtr(new Compress()));
messageHandleGroup.add(MessageHandlePtr(new Decompress()));
messageHandleGroup.execute(msg);
system("pause");
}