Adapter

„Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

Design Patterns: Elements of Reusable Object-Oriented Software

As you may have noticed, with Singleton, we reached the end of the creational patterns. From now on, we’ll consider the benefits of each so-called structural pattern. You don’t have to be a genius to find out what structural patterns are involved in: defining the composition of larger structures, built from objects.

The first one in the list is called Adapter (you may (and I have) known it as Wrapper). It comes handy when you are dealing with incompatible types (to be strict, interfaces). There are four players in the adapter pattern:

  • Target: that is, what the client can use, the shape we need to from the adaptee.
  • Client: our code which works with the Target.
  • Adaptee: an existing interface, that the client needs to use
  • Adapter: the class which acts as a wrapper, and adapts Adaptee to Target.

Maybe I haven’t described the problem in the best available way, so let’s see a code sample for this one:

interface ITarget
{
                void DoLegacyClientStuff();
}
class Adaptee:
{
                void DoNewStuff();
}
class Adapter: ITarget
{
                private Adaptee theAdaptee = new Adaptee();
                void DoLegacyClientStuff()
                {
                                theAdaptee.DoNewStuff();
                }
}

Now you can call the DoNewStuff method of the Adaptee by calling the Adapter’s DoLegacyStuff method. So Adapter acts as a wrapper around the new functionality. Whenever you need to conform two conflicting interfaces, make sure your adapt the Adapter pattern for the task!

Further Readings

Adapter Pattern in C #

Design Patterns (book): pp 139-150

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: