Sunday, March 27, 2022

SKP's GoF Design Patterns a Day - 05 - Adapter

[GitHub Repository for Code Samples]

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.

Adapter Pattern [Sample Code]
What can one do if he needs to use an Asian Hairdryer in a European Country, each with different socket types? I would seek an Adapter! As in real life, when we want to plug and play with similar but incompatible interfaces we use the Adapter. The Adapter adapts the Adaptee to the desired interface, by composing the Adaptee object and inheriting the desired interface or by multiple inheritance.
Fig. 1 : Adapter (Structural) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]

The attached example is a real world Computer scenario, where I want to plug in an external hard drive (pre-usb era!), SeagateDrive of interface type SeagateGeneric to an incompatible computer, SamsungComputer of type Computer. SeagateGeneric provides read() and write() methods for the specified purposes, which needs to be adapted to the actual bufferData(), flushData() and purgeData() methods of the Computer. Note that there is no equivalent of purgeData(). The ideal way to handle this scenario is to throw an exception, whenever this method is invoked on the hard drive as it would do in the real world. The adapter to perform the translation in this scenario is the SeagateAdapter, which implements the Computer interface. It encapsulates a SeagateGeneric instance reference, and adapts it to the Computer interface. Whenever a bufferData() method is invoked on the Computer interface, it actual requires three invocations of read() on the SeagateGeneric implementation to match up to the Computer’s standards. These kinds of translations are done by the adapte.

PCAssembler is the main class here. Try adding your own device and its adapter to the computer.

No comments: