FuzzDuck
FuzzDuck
Adapter pattern
FuzzDuck
Adapter pattern

Adapter pattern

There are two kinds of Adapter patterns. The first is the Class Adapter, the other is the Object Adapter. Both versions of the Adapter pattern have similar classes and methods. The purpose of theese patterns is to translate different methods, so they can be implemented by specific classes. An example is a class, which contains methods your application is unable to read. With the adapter pattern, you can create a class which translate the methods, and allows communication between different classes.

The difference between Class Adapter and Object Adapter

Class Adapter is using inheritance. It is associated with a specific class, and only translates the methods belonging to this class. Because of this, you would have to create multiple Adaptee classes, and Adapter methods which translates each Adaptee class’ methods. The Object Adapter gives the Adapter class knowledge of the Adaptee objects instantiated by the Adaptee interface/class. Here, the Adaptee class is concealed from the Client.

Class Adapter UML


Object Adapter UML

Dog translator

The Dog translator

A dog tries to communicate with its owner. The natural way for the dog to tell something could be through sounds or gestures. However, not every move comes out in an understandable way. With the Adapter pattern the methods of the dog can be translated into a context for the owner to understand through a specific class. We will call this class “Dog translator”. Comparing to the Adapter pattern, the scenario looks like this: Dog = Adaptee, Dog translator = Adapter, Owner = Target.

The foreigner, the local and the translator

With another case we have a foreigner speaking a foreign language, difficult for a local to make sense of. For the locals to understand the foreigner in his own language we need a translator to translate his sentences. Like the Dog translator, the foreigner is equal to the Adaptee class, which needs to be translated. The translator is the Adapter class, which adapts the foreign language for the local to understand. The Local is equal to the target, in which language we need the foreign one translate into.