Adaptor design patterns.

Two incompatible interfaces or systems can cooperate by using the adapter design pattern, a structural design pattern. Because of incompatible interfaces, it serves as a bridge between two classes that would not otherwise be able to communicate. The adapter approach is very helpful when attempting to incorporate third-party libraries or legacy code into a new system.


Real-World Example of Adapter Design Pattern

Let’s understand this concept using a simple example:

Suppose you have two buddies, one of them speaks French exclusively and the other English exclusively. The language barrier prevents them from communicating the way you want them to.

  • You act as an adapter, translating messages between them. Your role allows the English speaker to convey messages to you, and you convert those messages into French for the other person.
  • In this way, despite the language difference, your adaptation enables smooth communication between your friends.
  • This role you play is similar to the Adapter design pattern, bridging the gap between incompatible interfaces.

Scenario:

You have an app that expects to print text using a Printer interface.
But you found an old class called OldPrinter that doesn't fit your Printer interface.
You want to adapt it!


1. Target Interface (what the app expects)

java
public interface Printer { void print(String message); }

2. Adaptee (the old class)

java
public class OldPrinter { public void oldPrintMethod(String text) { System.out.println("Old Printer: " + text); } }

3. Adapter

java
public class PrinterAdapter implements Printer { private OldPrinter oldPrinter; public PrinterAdapter(OldPrinter oldPrinter) { this.oldPrinter = oldPrinter; } @Override public void print(String message) { oldPrinter.oldPrintMethod(message); // adapt the call } }

4. Client Code

java
public class Main { public static void main(String[] args) { OldPrinter oldPrinter = new OldPrinter(); Printer printer = new PrinterAdapter(oldPrinter); // adapt OldPrinter to Printer printer.print("Hello, World!"); // works through adapter } }

✨ Output:

sql
Old Printer: Hello, World!

Comments

Popular posts from this blog

Archunit test

visitor design pattern

Observer design pattern