http://en.wikipedia.org/wiki/Delegation_pattern
#include <iostream>
using namespace std;
class I {
public:
virtual void f() = 0;
virtual void g() = 0;
virtual ~I() {}
};
class A : public I {
public:
void f() { cout << "A: doing f()" << endl; }
void g() { cout << "A: doing g()" << endl; }
~A() { cout << "A: cleaning up." << endl; }
};
class B : public I {
public:
void f() { cout << "B: doing f()" << endl; }
void g() { cout << "B: doing g()" << endl; }
~B() { cout << "B: cleaning up." << endl; }
};
class C : public I {
public:
// construction/destruction
C() : i( new A() ) { }
virtual ~C() { delete i; }
private:
// delegation
I* i;
public:
void f() { i->f(); }
void g() { i->g(); }
// normal attributes
void toA() { delete i; i = new A(); }
void toB() { delete i; i = new B(); }
};
int main() {
C* c = new C();
c->f();
c->g();
c->toB();
c->f();
c->g();
return 1;
}
'Papers > Design pattern' 카테고리의 다른 글
mediator pattern (0) | 2007.12.18 |
---|---|
Flyweight pattern (0) | 2007.12.18 |
adapter pattern (0) | 2007.09.29 |
visitor pattern (0) | 2007.09.02 |
factory method (0) | 2007.07.08 |