Adapter Design Pattern in Java

It is a pattern in which 2 unrelated interfaces can work with each other. The two interfaces interact with each other with the help of an adapter.

Client invokes the target interface via the adapter but he is unaware of the adapter’s presence.

Consider a case in which client asks for Tea via a Vending Machine. But Tea is not available and Coffee should be provided to the client.

Here Tea and Coffee are separate Classes with separate interfaces. Against Coffee we need to book a Tea so they need to interact with each other. Let’s see how it happens.

We have Design 2 classes which are Tea and Coffee with their Respective Interfaces.

interface CoffeeMaker 
{ 
    void makeCoffee(); 
} 
  
class Coffee implements CoffeeMaker 
{ 
    public void makeCoffee() 
    { 
        System.out.println("Coffee is created and dispatched"); 
    } 
} 
  
interface TeaMaker 
{ 
    void makeTea(); 
} 
  
class Tea implements TeaMaker 
{ 
    public void makeTea() 
    { 
        System.out.println("Tea is created and dispatched"); 
    } 
} 

Let’s create a adapter which would implement the Tea Interface but delivers an Coffee.

class CoffeeAdapter implements TeaMaker 
{ 
    Coffee coffee; 
    public CoffeeAdapter(Coffee coffee) 
    { 
        // we need reference to the object we 
        // are adapting 
        this.coffee = coffee; 
    } 
  
    public void makeTea() 
    {  
        coffee.makeCoffee(); 
    } 
} 

So here we have an CoffeeAdapter which implements the tea interface but provides them a Coffee.

Let’s implement the main class to run the complete flow.

class AdapterExample
{ 
    public static void main(String args[]) 
    { 
        Coffee cof = new Coffee(); 
        TeamMaker tm = new CoffeeAdapter(); 
  
        //Wrap the coffee object inside and adapter so that it behaves as a order for Tea
        TeaMaker tm = new CoffeeAdapter(cof); 
  
        System.out.println("Create tea"); 
        tm.makeTea();
 
    } 
} 

O/P:
Create Tea.
Coffee is created and dispatched.