Adapter design pattern:
In this post, we will try to explain the importance of an adapter design pattern with real-time examples. It is one of the structural patterns. it converts an interface to another user expected interface. it works as a bridge between two separate interfaces. the adapter does the conversion and translation too.beauty of adapter design pattern, It combines the capabilities of two interfaces. now let’s explain this with real-time examples.
Mobile charge:
- mobile charger acts as an adapter between mobile and power socket.
- plug charger pin to mobile
- put the charger into a wall socket.
A compiler:
The compiler accepts and processes programming statements and turns them into machine code which the machine understands.
we do not solve any issue with changes to existing code or third party code. but we will write code in such a way that adapts the new third party code into existing code. it works as a mediator between third-party code and existing code. adapter receives the request and parses them into requests that are supported by the vendor.
Real example for adapter pattern in java programming:
public class AdapterPatternDemo {
public static void main(String[] args) {
Duck d1 = new DomesticDuck();
d1.quack();
Turkey t1 = new DomesticTurkey();
TurkeyAdapter adapter=new TurkeyAdapter(t1);
adapter.quack();
/** passing the duck object to some method ***/
duckSound(d1);
duckSound(adapter);
}
static void duckSound(Duck d)
{
d.quack();
}
}
interface Duck
{
void quack();
}
class DomesticDuck implements Duck
{
@Override
public void quack() {
System.out.println("quack quack.....");
}
}
interface Turkey
{
void gobble();
}
class DomesticTurkey implements Turkey
{
@Override
public void gobble() {
System.out.println("gobble sound...");
}
}
class TurkeyAdapter implements Duck
{
Turkey turkeyinterface;
public TurkeyAdapter(Turkey turkeyinterface) {
this.turkeyinterface = turkeyinterface;
}
@Override
public void quack() {
this.turkeyinterface.gobble();
}
}
in the above example, TurkeyAdapter class implements the Duck interface. and has a turkey interface variable. we have implemented the quack method in the class but we are calling the gobble method of turkey class in it.
we can pass turkey instance variables and duck instance variables to the same method duckSound(). we no need to create a separate method for turkey and duck individually. we can use a single adapter class to combine them into one. with help of this, code length will be reduced and it improves the performance of your application.
i hope you all understood the purpose of the adapter design pattern with real time example. thanks 🙂
Leave a comment