Wzorzec łańcuch odpowiedzialności łączy w postaci listy obiekty żądań.
Każde żądanie, jako element łańcucha, realizuje pewne zadanie. Jeżeli realizacja żądania powiedzie się, kończy się proces dalszych wywołań. W przeciwnym wypadku realizowane jest kolejne żądanie z łańcucha aż do dotarcia do ostatniego elementu.
#include <iostream>
#include <vector>
class CHandle
{
public:
virtual bool HandleIt() = 0;
virtual ~CHandle() {}
};
class CActionA : public CHandle
{
public:
bool HandleIt()
{
std::cout << "CActionA::HandleIt()" << std::endl;
return false;
}
};
class CActionB : public CHandle
{
public:
bool HandleIt()
{
std::cout << "CActionB::HandleIt()" << std::endl;
return false;
}
};
class CActionC : public CHandle
{
public:
bool HandleIt()
{
std::cout << "CActionC::HandleIt()" << std::endl;
return true;
}
};
class CActions : public CHandle
{
std::vector<CHandle*> chain;
public:
CActions()
{
chain.push_back(new CActionA());
chain.push_back(new CActionB());
chain.push_back(new CActionC());
}
bool HandleIt()
{
std::vector<CHandle*>::iterator it = chain.begin();
while (it != chain.end())
if ((*it++)->HandleIt())
return true;
std::cout << "No action handle it!" << std::endl;
return false;
}
~CActions()
{
std::vector<CHandle*>::iterator it = chain.begin();
while (it != chain.end())
{
delete *it;
*it++ = 0;
}
chain.clear();
}
};
int main(int nArguments, char* szArguments[])
{
CActions chain;
chain.HandleIt();
return 0;
}
0 Komentarzy