Thursday, April 19, 2012

Structural Patterns - 1.Adapter Pattern

So far, we discussed about the ways of creating an object and patterns involved during object creation.

Next we are going to see about the Structural patterns. They mostly deal with the way the classes or interfaces or represented or related. The influence of class structures on achieving a functionality will be widely discussed with a set of patterns.

Adapter Pattern

This is one among the most frequently used Design Patterns. The main benefit in going for the Adapter pattern, is to establish proper communication between two or more incompatible interfaces. In otherwords, adapter makes two different interfaces communicate each other.

There are two types of Adapters,
a) Class Adapters and
b) Object Adapters

Class Adapters

Consider, there are two different interfaces requires communication between each other. The Adapter class will inherit both the interfaces and overrides the implementation by custom code. Message from one interface will be taken and customized in such a way the other interface could process it.

A simple example of Class Adapters can be seen below,



In the above design, we want to transfer some data from a USB device to an HDMI device. So, we defined an Adapter class USBHDMIAdapter by inheriting both USBSource and HDMISource.

While writing the implementation for the method getHDMIData(), we internally fetch the USBData and perform customizations in order to make the data compatible with HDMI. Finally return the data back to the HDMI Source.

Sample code snippet for better understanding,

In the Adapter class we write our implementation for the getHDMIData() as follows,
public String getHDMIData() {
String hdmiData=getData().replace("USB", "HDMI");
return hdmiData;
}


and in the Client class we can invoke the Adapter as stated below,

USBSource usbSource=new USBSource();
usbSource.setData("USB Movie - 123");

HDMISource hdmiSource=new USBHDMIAdapter(usbSource);
System.out.println(hdmiSource.getHDMIData());


Object Adapters

They are very much similar to the Class Adapters but instead of generalization we use composition. We compose the USBSource object and write implementation for the HDMISource with our custom code.

Following design explains the Object Adapter pattern,



The source code for defining the Object Adapter may look as specified below,

class USBHDMIAdapter implements HDMISource{

private USBSource usbSource;

public USBHDMIAdapter(USBSource source) {
this.usbSource=source;
}

@Override
public String getHDMIData() {
String hdmiData=usbSource.getData().replace("USB", "HDMI");
return hdmiData;
}

}

No comments:

Post a Comment