Adapter pattern and delegate objects

Started by
1 comment, last by WoopsASword 7 years, 8 months ago

I am studying Design Patterns by the gof, and I am having a little bit of a time trying to wrap my head around the idea of delegate objects in the context of the Adapter pattern. Is the purpose of a delegate to simply keep a narrow interface of the Adapter object to the client? That does not even seem necessary because the adapter already has an association with the client. The delegate pattern forms a circular association.

What am I missing here?

For those with the book, I am referring to page 144 - 145, Chapter 4

Advertisement
Roughly speaking, the adapter pattern is when you make a wrapper to retrofit one interface to work as a different interface. Delegation is when you forward functionality to another object. A delegate is a very natural way to implement an adapter when you, assuming you approach problems by trying to slap design patterns into everything (which is terrible engineering).

class MyObject {
  public void something();
};

class Interface {
  abstract void act();
};

class Adapter inherits Interface {
  private ref MyObject _delegate;

  void act() { // Adapter is _adapting_ MyObject to Interface...
    _delegate.something(); // ... by delegating/forwarding to the Real object
  }
};

Sean Middleditch – Game Systems Engineer – Join my team!

Think of "delegation" in terms of composition (when we speak in terms of object oriented design).

You include a different behavior rather than contain it directly. Composition is one of the most powerful tools in design.

The adapter uses both composition and inheritance to chain the relevant behavior.

An example:

LegacySword is an old component which we want to wrap around our new design.

Class LegacySword

{ void Stab(...) {...} // Stab is a method from the old design, we might not change it so easily, so we create adaptation.

// The new mechanics.

interface IWeapon{

void Attack();

}

class sword extends IWeapon{

private:

LegacySword instance;

public:

void Attack(...)

{ ... instance.Stab(...) ... }

}

It's a silly example but you might get the point.

Use adapter when you deal with old code, if you write adapters in your new designs then something might be wrong with them

This topic is closed to new replies.

Advertisement