You are on page 1of 2

Adapter Tip i scop: ablon structural; cum se compun clasele i obiectele pentru a forma structuri mai mari; permite

reutilizarea codului surs vechi i incompatibil (legacy code); Solu ie: un intermediar (Adapter) permite unor clase cu interfe e incompatibile (Target i Adaptee) s lucreze mpreun ;

Participan i: Target: declararea interfe ei pe care clientul o va utiliza; Adaptee: declararea interfa ei ce trebuie adaptat (legacy code); Adapter: adapteaz interfa a Adaptee cu interfa a Target; Exemplu:
#include <iostream> using namespace std; class ITarget { public: virtual void executeRequest() = 0; virtual ~ITarget(){} }; // adapter class template <class TYPE> class Adapter: public ITarget { /* the old */ private: TYPE* object; // ptr-to-object attribute void (TYPE::* method)(); // ptr-to-member-function attribute public: Adapter( TYPE* object, void (TYPE::* method)() ) { this->object = object; this->method = method; } ~Adapter() { // the object will be created with new delete object; }

// the adapter "maps" the new to the old void executeRequest() { (object->*method)(); } };

// three old totally incompatible classes // no common base, no polymorphism class A { public: void doThis() { cout << "A::doThis()" << endl; } }; class B { public: void doThat() { cout << "B::doThat()" << endl; } }; class C { public: void doTheOther() { cout << "C::doTheOther()" << endl; } }; int main() { // one Adapter for each of those classes ITarget* adapters[3]; adapters[0] = new Adapter <A> ( new A(), &A::doThis ); adapters[1] = new Adapter <B> ( new B(), &B::doThat ); adapters[2] = new Adapter <C> ( new C(), &C::doTheOther );

for (int i = 0; i<3; ++i) { // "external polymorphism" adapters[i]->executeRequest(); } for (i = 0; i < 3; i++) { delete adapters[i]; } return 0; }

Observa ie: Exemplul anterior demonstreaz utilizarea pattern-ului pentru a induce polimorfismul din exterior, atunci cnd acesta nu exist .

You might also like