Adapter Design Pattern in Java
Type : Structural Design Pattern
Summary
Adapter design pattern is a Structural design pattern. It is used to provides compatible interface for and Class so that can be used by Client. Adapter pattern is used to provide compatibility for Classes which already exists and cannot be modified.
Details
Need for adapter design pattern is very obvious. It is also very common in real world as well as in Software Engineering. For instance if we have any electrical appliances which runs on 110 Volt and then we travel to a country where the electricity supply is 220 V. We cannot change or modify the electric connection to provide us 110 V. Rather we can use a adapter to convert the 220 V from outlet to 110V.
Adapter pattern is similar to Bridge pattern because both provide mechanism to connect incompatible Classes.
Advantages
Incompatible Object or Class can be used using an Adapter for it.
Disadvantages
Increases number of Classes
Adapter Class needs to be modified if the Target Classes changes.
Example
For instance if we consider a TV set which has input connector as USB. We can connect any device which has USB port.
Now say a new device launched "Blue Ray DVD" which has HDMI as output. We cannot connect this two devices as they are not compatible .
We make them work together by providing an adapter HDMIToUSBAdapter which converts HDMI to USB and vice versa
Class Diagram
Sample Code
// TV which connects though USB port
public class TV {
private USBConnectorPlayer connect;
public void connectTVAndPlay(USBConnectorPlayer conn) {
this.connect(conn);
this.connect.renderContent();
}
public void connect(USBConnectorPlayer connect) {
this.connect = connect;
}
}
// USB connector player
public class USBConnectorPlayer {
private String content;
public USBConnectorPlayer(String content) {
this.content = content;
}
public void renderContent() {
System.out.println(this.content);
}
}
// a player that supports HDMI connection
public class HDMIConnectorPlayer {
private StringBuffer content;
public HDMIConnectorPlayer(StringBuffer content) {
this.content = content;
}
public void renderContent() {
System.out.println(this.content);
}
public StringBuffer getContent() {
return content;
}
}
package blog.javaexp.structural.adapter;
// Adapter Class to convert HDMI to USB
public class HDMIToUSBAdapter {
public USBConnectorPlayer convertToUSB(HDMIConnectorPlayer hdmi) {
String str = hdmi.getContent().toString();
USBConnectorPlayer ret = new USBConnectorPlayer(str);
return ret;
}
}
Comments
Post a Comment