The Artima Developer Community
Sponsored Link

Heron-Centric: Ruminations of a Language Designer
The Generic Adapter Pattern
by Christopher Diggins
August 15, 2005
Summary
C++ templates enable a powerful variant of the Adapter Pattern, which I call the Generic Adapter Pattern. I think it helps illustrate how OO design patterns go together well with generic programming techniques.

Advertisement

The Generic Adapter Pattern, shows off a bit of the power of C++ templates. The way it works is as follows: say you have a client (DuckListener) which requires an object which implements a specific interface (DuckInterface). If you want to use another object (Dog) which is not an explicit subtype you have to create an adapter. Here is example of how you could use the GoF Adapter Design Pattern:

struct DuckInterface {
  virtual string Quack() = 0;
}

struct DuckListener {
  void Listen(DuckInterface& d) {
    cout << "the duck quacks like this " << d.Quack() << endl;
  }
}

struct Dog {
  void Quack {
    return "woof";
  }
}

struct DogToDuckAdapter : DuckInterface {
  DogToDuckAdapter(Dog* x) : m(x) { }
  virtual string Quack() { return m->Quack(); }
  Dog* m;
}

int main() {
  Dog dog;
  DuckListener listener;  
  DogToDuckAdapter ducklike(&dog);
  listener.Listen(ducklike);
}
Now here is how the Generic Adapter Pattern works:
template<typename T>
struct GenericDuckAdapter : DuckInterface {
  GenericDuckAdapter(T* x) : m(x) { }
  virtual string Quack() { return m->Quack(); }
  T* m;
}

int main() {
  Dog dog;
  DuckListener listener;
  GenericDuckAdapter<dog> ducklike(&dog); 
  listener.Listen(ducklike);
}
The usefulness of the generic approach hopefully becomes more apparent when you consider that when you need to make other things duck-like, the non-generic approach becomes quickly very redundant.

I wonder who is researching this kind of stuff, any ideas? It seems to me that someone should write a book about generic design patterns in C++. Out of curiosity would you be interested in such a book?

Talk Back!

Have an opinion? Readers have already posted 10 comments about this weblog entry. Why not add yours?

RSS Feed

If you'd like to be notified whenever Christopher Diggins adds a new entry to his weblog, subscribe to his RSS feed.

About the Blogger

Christopher Diggins is a software developer and freelance writer. Christopher loves programming, but is eternally frustrated by the shortcomings of modern programming languages. As would any reasonable person in his shoes, he decided to quit his day job to write his own ( www.heron-language.com ). Christopher is the co-author of the C++ Cookbook from O'Reilly. Christopher can be reached through his home page at www.cdiggins.com.

This weblog entry is Copyright © 2005 Christopher Diggins. All rights reserved.

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use