Design Pattern Basic Tutorial

adplus-dvertising
Adapter Pattern
Previous Home Next

The Adapter pattern is very useful structural pattern because with help of this we can established the relationship between the different types of the interfaces and prepare for work together. This means that it is convert to one interface of one class to an other interface expected by the client. lets take an example To understand clearly.

Example

Suppose that there are many sockets of different shapes and sizes in a home. socket has variation in sizes, and all sockets have no capability of plug-in a laptop adapter. then for make the portable it we can use the adapter. Here we are use the Adapter as a connector. This connector connects them together and complete the client requirement.

Benefit of Adapter Pattern

The developer is use this pattern to relate the different type of the class such as they work together in a program. this is provide the compatibility between interfaces and classes and also provide the pluggable kit, delegates objects and make the classes highly reusable and it is help to achieving the goal through inheritance or composition.

Adapter Pattern is also trying to match the interfaces such as WindowAdapter, MouseAdapter, KeyAdapter, ComponentAdapter, ContainerAdapter, FocusAdapter and MouseMotionAdapter.

Example

//Create the Interface
package r4r;
public interface Switch {
void SwitchOn();
void Switchoff();
}
// Create the Room class and implement to interface

package r4r;
public class bulb implements Switch {
public void SwitchOn()
{
System.out.println("bulb is on");
}
public void Switchoff()
{
System.out.println("bulb is off");
}
}

// Create the bulb class and implement to the interface
package r4r;
import java.util.*;
public class fam implements Switch {
public void SwitchOn()
{
System.out.println("fan is on");
}
public void Switchoff()
{
System.out.println("fan is off");
}

}
package r4r;
public class adaptertests {
public static void main(String[] args)
{
fam f= new fam();
bulb b=new bulb();
f.SwitchOn();
f.Switchoff();
b.Switchoff();
b.SwitchOn();
}
}
Previous Home Next