Sign in to follow this  
ExErvus

Adapter pattern and delegate objects

Recommended Posts

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

Share this post


Link to post
Share on other sites
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
  }
};

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this