chain.h
#pragma once
#include <QDebug>
class CHandle
{
public:
CHandle():m_handle(0){}
CHandle(CHandle *hadle):m_handle(hadle){}
virtual ~CHandle()
{
if (m_handle)
{
delete m_handle;
}
}
virtual void handleRequest() = 0;
virtual void setHandle(CHandle* handle) = 0;
virtual CHandle* getHandle() const = 0;
protected:
CHandle *m_handle;
};
class CConcreateHandleA : public CHandle
{
public:
CConcreateHandleA():CHandle(0){}
CConcreateHandleA(CHandle *hadle):CHandle(hadle){}
virtual ~CConcreateHandleA(){}
void handleRequest();
void setHandle(CHandle* handle);
CHandle* getHandle() const;
};
class CConcreateHandleB : public CHandle
{
public:
CConcreateHandleB():CHandle(0){}
CConcreateHandleB(CHandle *hadle):CHandle(hadle){}
virtual ~CConcreateHandleB(){}
void handleRequest();
void setHandle(CHandle* handle);
CHandle* getHandle() const;
};
chain.cpp
#include "chain.h"
void CConcreateHandleA::handleRequest()
{
if (m_handle)
{
m_handle->handleRequest();
}
else
{
qDebug() << "A handle";
}
}
void CConcreateHandleA::setHandle(CHandle* handle)
{
m_handle = handle;
}
CHandle* CConcreateHandleA::getHandle() const
{
return m_handle;
}
void CConcreateHandleB::handleRequest()
{
if (m_handle)
{
m_handle->handleRequest();
}
else
{
qDebug() << "B handle";
}
}
void CConcreateHandleB::setHandle(CHandle* handle)
{
m_handle = handle;
}
CHandle* CConcreateHandleB::getHandle() const
{
return m_handle;
}
main.cpp
#include <QApplication>
#include "chain.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
CHandle *hadleA = new CConcreateHandleA();
CHandle *hadleB = new CConcreateHandleB(hadleA);
hadleA->handleRequest();
hadleB->handleRequest();
return app.exec();
}