top of page
Search
Writer's pictureAbhinaw Tripathi

Design Pattern - Adapter Design Pattern


What is Adapter Pattern?

Of-curse,a structural design pattern which converts the existing interfaces to a new interface to achieve compatibility and reusable of the unrelated classes in one application.

Adapter pattern is also known as Wrapper pattern. An adapter allows classes to work together that normally could not because of incompatible interfaces.the adapter also responsible for transforming data into appropriate forms.

Example: 2 pin and 3 pin problem.let say we have a 3 pin plug and 2 pin power socket then we use an intermediate adapter and fit the 3 pin cable to it and attach adapter to 2 pin power socket.

There are two ways of implementing the Adapter pattern,

  • Using Inheritance[Class adapter]

  • Using Composition[Object adapter]

Implementation using Inheritance:

public class Plug

{

private String specification;

private String getInput()

{

return specification;

}

public Plug()

{

this.specification="3-Pin";

}

}

public interface Socket

{

public String getInput();

}

public class ExpansionAdapter implements Socket,extends Plug

{

public String getInput()

{

String input=super.getInput();

input=input+"power converted to 2-Pin"

return input;

}

}

public class Client

{

private Socket socket;

public void finctiontest()

{

socket = new ExpansionAdapter();

socket.getInput();

}

}

Implementation using Composition:

Instead of inheritance the base class create adapter by having the base as attribute inside the adapter.So we can access all the methods by having attributes.This is a Composition.

public class Plug

{

private String specification;

private String getInput()

{

return specification;

}

public Plug()

{

this.specification="3-Pin";

}

}

public interface Socket

{

public String getInput();

}

public class ExpansionAdapter implements Socket

{

private Plug plug;

ExpansionAdapter(Plug plug)

{

this.plug=plug;

}

public String getInput()

{

String input=super.getInput();

input=input+"power converted to 2-Pin"

return input;

}

}

public class Client

{

private Socket socket;

public void finctiontest()

{

socket = new ExpansionAdapter();

socket.getInput();

}

}

When to use Adapter Pattern:

  • When a class that you need to use does not meet the requirement of an interface.

  • For a particular object to contribute to the Properties view,adapter are used display the objects data.

Disadvantage of using Adapter Pattern:

due to additional layer of code added and so to maintain but if rewriting existing code is not an option,adapters provide a good option.

Types of Adapters

  1. Class Adapter = They adapt adaptee to target by committing to a concrete Adapter class

  2. Object Adapter

  3. Pluggable Adapter= These are classes with many Adaptees that is the Adaptee itself

9 views0 comments

Recent Posts

See All
bottom of page