The Adapter Pattern is one of the easiest to understand and relate to the real world.  We see adapters used every day and they have become a critical factor in our daily success.  Almost every device we have utilizes an adapter in some way.

The Adapter Pattern Defined

As always, we will start with the “Gang of Four” definition to set the stage for our discussion.

“Ensure a class only has one instance, and provide a global point of access to it.”

There are many names for an adapter pattern.  However, they all imply the same thing.  The implementation boils down to a translator between two parties.  A commonly experienced real-world example is a power or recharging adapter.  These accessories translate the power coming out of the wall to the input for the device.  The software approach is not fundamentally different.

Applying The Pattern

It is hard to imagine software without adapters.  In particular, the ideas of abstraction and implementation hiding would be impossible without an adapter.  That makes this pattern a solution to one of the most critical requirements of object-oriented applications and flexible software of any type.

The implementation of this pattern is a simple structure.  There is an input/interface that talks to one object and it has an output/interface talking to another object.  The details often are handled by a class being the input/output of the method and the adapter translates from that object to recognizable parameters.  Those values are used to make a call and then the results are passed back to the caller.

Java, PHP, C#, etc.

The alternative of an adapter pattern is pulling values out of one object, translating them to a method on another class, and then repeating the process for the results.  There is nothing special about the solution outside of an interface.  The interface is what we are adapting to.  Thus, if we want to create an adapter for an employee to treat them as a contact like a customer we need an interface of CustomerAdpater that takes an employee instance.  Under the covers, the adapter translates the employee data to similar customer data for contacts and then implements the needed methods.  It all boils down to a map or translation step although it can sometimes be a complicated process.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a lifetime learner as a developer, designer, and manager of software solutions. Rob is the founder of RB Consulting and has managed to author a book about his family experiences and a few about becoming a better developer. In his free time, he stays busy raising five children (although they have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax or working on his ballroom dance skills.

Leave a Reply