[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]
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.