reference material: http://www.runoob.com/w3cnote/delegate-mode.html
Delegation pattern is a basic skill in software design pattern. In the delegation mode, there are two objects participating in the same request, and the object accepting the request delegates the request to another object. Delegation mode is a basic skill. Many other modes, such as state mode, policy mode and visitor mode, essentially adopt delegation mode in more special occasions. The delegate pattern allows us to replace inheritance with aggregation, and it also allows us to simulate mixin s.
//*****************************************************************************
//*** Delegation mode (example 1) ***
//*****************************************************************************
#include <iostream>
using namespace std;
class RealPrinter {
public:
void print() { std::cout << "real-printer" << std::endl; }
};
class Printer {
public:
Printer() : p(RealPrinter()) {}
void print() { p.print(); }
private:
RealPrinter p;
};
int main()
{
Printer* printer = new Printer();
printer->print();
}
//*****************************************************************************
//*** Delegation mode (example 2)***
//*****************************************************************************
#include <iostream>
using namespace std;
class I //interface {
public:
virtual void f() = 0;
virtual void g() = 0;
};
class A : public I {
public:
void f(){std::cout << "A::f()" << std::endl;}
void g(){std::cout << "A::g()" << std::endl;}
};
class B : public I {
public:
void f(){std::cout << "B::f()" << std::endl;}
void g(){std::cout << "B::g()" << std::endl;}
};
class C : public I {
public:
C() { m_i = new A();/*delegation*/ }
void f(){ m_i->f(); }
void g(){ m_i->g(); }
// normal attributes
void toA(){ m_i = new A(); }
void toB(){ m_i = new B(); }
private:
I* m_i;
}
int main()
{
C cc = C();
cc.f(); // output: A::f()
cc.g(); // output: A::g()
cc.toB();
cc.f(); // output: B::f()
cc.g(); // output: B::g()
}