Structural design patterns: Adaptor design pattern

 

Adapter Design Pattern

Adapter Design Pattern is a structural pattern that acts as a bridge between two incompatible interfaces, allowing them to work together. It is especially useful for integrating legacy code or third-party libraries into a new system.

Explain the Diagram:

  • Client wants to use a Target interface (it calls Request()).
  • Adaptee already has useful functionality, but its method (SpecificRequest()) doesn’t match the Target interface.
  • Adapter acts as a bridge: it implements the Target interface (Request()), but inside, it calls the Adaptee’s SpecificRequest().
  • This allows the Client to use the Adaptee without changing its code.
For example

2. Adaptee (LegacyPrinter)

class LegacyPrinter {
    public void printDocument() {
        System.out.println("Legacy Printer is printing a document.");
    }
}
Suppose we have to introduce a new printer, then its a adaptee, 
we will introduce a new interface

1. Target Interface (Printer)

The interface that the client code expects.

interface Printer {

    void print();

}

now we are implementing a new class to adapt legacy print fuctionality with print interface.

3. Adapter (PrinterAdapter)

class PrinterAdapter implements Printer {

    private LegacyPrinter legacyPrinter;


    public PrinterAdapter(LegacyPrinter legacyPrinter) {

        this.legacyPrinter = legacyPrinter;

    }


    @Override

    public void print() {

        legacyPrinter.printDocument();

    }

}


4. Client Code

// Client Code

public class Client {

    public static void clientCode(Printer printer) {

        printer.print();

    }


    public static void main(String[] args) {

        // Using the Adapter

        PrinterAdapter adapter = new PrinterAdapter();

        clientCode(adapter);

    }

}

Comments

Popular posts from this blog

Archunit test

Hexagonal Architecture

visitor design pattern