#include <iostream>
#include <string>
#include <memory>
enum class TYPE
{
REQ1,
REQ2,
REQ3
};
class request
{
public:
request(const std::string& msg, TYPE type):m_sMsg(msg),t(type)
{
}
~request()
{
}
TYPE getType() const
{
return t;
}
private:
std::string m_sMsg;
TYPE t;
};
class chainHanlder
{
public:
chainHanlder()
{
}
virtual ~chainHanlder()
{
}
void setNextHandle(const std::shared_ptr<chainHanlder> &p)
{
m_pNext = p;
}
void handle(const request& q)
{
if (can(q))
{
process(q);
}
else
{
nextChainProcess(q);
}
}
protected:
virtual bool can(const request& q) = 0;
virtual void process(const request& q) = 0;
private:
void nextChainProcess(const request& q)
{
if (m_pNext)
{
m_pNext->process(q);
}
}
private:
std::shared_ptr<chainHanlder> m_pNext;
};
class Handle1 : public chainHanlder
{
protected:
virtual bool can(const request& q)
{
return q.getType() == TYPE::REQ1;
}
virtual void process(const request& q)
{
std::cout << "handle1" << std::endl;
}
};
class Handle2 : public chainHanlder
{
protected:
virtual bool can(const request& q)
{
return q.getType() == TYPE::REQ2;
}
virtual void process(const request& q)
{
std::cout << "Handle2" << std::endl;
}
};
int main()
{
std::shared_ptr<Handle1> h1 = std::make_shared<Handle1>();
std::shared_ptr<Handle2> h2 = std::make_shared<Handle2>();
h1->setNextHandle(h2);
request q("aa", TYPE::REQ2);
h1->handle(q);
return 0;
}
本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2021/05/18 14:23