The Wayback Machine - https://web.archive.org/web/20240928070346/https://www.geeksforgeeks.org/adapter-pattern/
Open In App

Adapter Design Pattern

Last Updated : 04 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Adapter design pattern is a structural pattern that allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces, making them work together. This pattern involves a single class, known as the adapter, which is responsible for joining functionalities of independent or incompatible interfaces.

adapter-design-pattern

Let’s understand this concept using a simple example:

Let’s say you have two friends, one who speaks only English and another who speaks only French. You want them to communicate, but there’s a language barrier.

  • 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.

Components of Adapter Design Pattern

1. Target Interface

  • Description: Defines the interface expected by the client. It represents the set of operations that the client code can use.
  • Role: It’s the common interface that the client code interacts with.

2. Adaptee

  • Description: The existing class or system with an incompatible interface that needs to be integrated into the new system.
  • Role: It’s the class or system that the client code cannot directly use due to interface mismatches.

3. Adapter

  • Description: A class that implements the target interface and internally uses an instance of the adaptee to make it compatible with the target interface.
  • Role: It acts as a bridge, adapting the interface of the adaptee to match the target interface.

4. Client

  • Description: The code that uses the target interface to interact with objects. It remains unaware of the specific implementation details of the adaptee and the adapter.
  • Role: It’s the code that benefits from the integration of the adaptee into the system through the adapter.

Adapter Design Pattern Example

Problem Statement

Let’s consider a scenario where we have an existing system that uses a LegacyPrinter class with a method named printDocument() which we want to adapt into a new system that expects a Printer interface with a method named print(). We’ll use the Adapter design pattern to make these two interfaces compatible.

Class-Diagram-of-Adapter-Design-Pattern_

1. Target Interface (Printer)

The interface that the client code expects.

C++




// Target Interface
 
class Printer {
public:
    virtual void print() = 0;
};


2. Adaptee (LegacyPrinter)

The existing class with an incompatible interface.

C++




// Adaptee
 
class LegacyPrinter {
public:
    void printDocument() {
        std::cout << "Legacy Printer is printing a document." << std::endl;
    }
};


3. Adapter (PrinterAdapter)

The class that adapts the LegacyPrinter to the Printer interface.

C++




// Adapter
 
class PrinterAdapter : public Printer {
private:
    LegacyPrinter legacyPrinter;
 
public:
    void print() override {
        legacyPrinter.printDocument();
    }
};


4. Client Code

The code that interacts with the Printer interface.

C++




// Client Code
 
void clientCode(Printer& printer) {
    printer.print();
}


Complete Code for the above example:

C++




// Adapter Design Pattern Example Code
 
#include <iostream>
 
// Target Interface
class Printer {
public:
    virtual void print() = 0;
};
 
// Adaptee
class LegacyPrinter {
public:
    void printDocument() {
        std::cout << "Legacy Printer is printing a document." << std::endl;
    }
};
 
// Adapter
class PrinterAdapter : public Printer {
private:
    LegacyPrinter legacyPrinter;
 
public:
    void print() override {
        legacyPrinter.printDocument();
    }
};
 
// Client Code
void clientCode(Printer& printer) {
    printer.print();
}
 
int main() {
    // Using the Adapter
    PrinterAdapter adapter;
    clientCode(adapter);
 
    return 0;
}


Output

Legacy Printer is printing a document.



How Adapter Design Pattern works?

  1. Client Request:
    • The client initiates a request by calling a method on the adapter using the target interface.
  2. Adapter Translation:
    • The adapter translates or maps the client’s request into a form that the adaptee understands, using the adaptee’s interface.
  3. Adaptee Execution:
    • The adaptee performs the actual work based on the translated request from the adapter.
  4. Result to Client:
    • The client receives the results of the call, remaining unaware of the adapter’s presence or the specific details of the adaptee.

Why do we need Adapter Design Pattern?

  1. Integration of Existing Code:
    • Scenario: When you have existing code or components with interfaces that are incompatible with the interfaces expected by new code or systems.
    • Need: The Adapter pattern allows you to integrate existing components seamlessly into new systems without modifying their original code.
  2. Reuse of Existing Functionality:
    • Scenario: When you want to reuse classes or components that provide valuable functionality but don’t conform to the desired interface.
    • Need: The Adapter pattern enables you to reuse existing code by creating an adapter that makes it compatible with the interfaces expected by new code.
  3. Interoperability:
    • Scenario: When you need to make different systems or components work together, especially when they have different interfaces.
    • Need: The Adapter pattern acts as a bridge, allowing systems with incompatible interfaces to collaborate effectively.
  4. Client-Server Communication:
    • Scenario: When building client-server applications, and the client expects a specific interface while the server provides a different one.
    • Need: Adapters help in translating requests and responses between client and server, ensuring smooth communication despite interface differences.
  5. Third-Party Library Integration:
    • Scenario: When incorporating third-party libraries or APIs into a project, and their interfaces do not match the rest of the system.
    • Need: Adapters make it possible to use external components by providing a compatible interface for the rest of the application.

When not to use Adapter Design Pattern?

  1. When Interfaces Are Stable:
    • Scenario: If the interfaces of the existing system and the new system are stable and not expected to change frequently.
    • Reason: Adapters are most beneficial when dealing with evolving or incompatible interfaces. If the interfaces are stable, the overhead of maintaining adapters might outweigh the benefits.
  2. When Direct Modification Is Feasible:
    • Scenario: If you have control over the source code of the existing system, and it’s feasible to directly modify its interface to match the target interface.
    • Reason: If you can modify the existing code, direct adaptation of interfaces might be a simpler and more straightforward solution than introducing adapters.
  3. When Performance is Critical:
    • Scenario: In performance-critical applications where the overhead introduced by the Adapter pattern is not acceptable.
    • Reason: Adapters may introduce a level of indirection and abstraction, which could have a minor impact on performance. In situations where every bit of performance matters, the Adapter pattern might not be the best choice.
  4. When Multiple Adapters Are Required:
    • Scenario: If a system requires numerous adapters for various components, and the complexity of managing these adapters becomes overwhelming.
    • Reason: Managing a large number of adapters might lead to increased complexity and maintenance challenges. In such cases, reconsider the overall design or explore alternatives.
  5. When Adapters Introduce Ambiguity:
    • Scenario: When introducing adapters leads to ambiguity or confusion in the overall system architecture.
    • Reason: If the presence of adapters makes the system design less clear or harder to understand, it may be worthwhile to explore alternative solutions that offer a clearer design.



Previous Article
Next Article

Similar Reads

Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Adapter Pattern | C++ Design Patterns
Adapter Pattern is a structural design pattern used to make two incompatible interfaces work together. It acts as a bridge between two incompatible interfaces, allowing them to collaborate without modifying their source code. This pattern is particularly useful when integrating legacy code or third-party libraries into your application. Important T
6 min read
Adapter Design Pattern in Java
The Adapter design pattern in Java is a structural pattern that allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces, making them work together. This pattern involves a single class, known as the adapter, which is responsible for joining functionalities of independent or
7 min read
Adapter Method - Python Design Patterns
Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces.
4 min read
Difference Between the Facade, Proxy, Adapter, and Decorator Design Patterns
Understanding design patterns is crucial for software developers. Facade, Proxy, Adapter, and Decorator are key patterns that address different aspects of software design, from simplifying interfaces to enhancing functionality. This article explores their distinctions and practical applications in software development. Important Topics for Facade v
4 min read
Adapter Method | JavaScript Design Patterns
Adapter Pattern in JavaScript is a structural design pattern that allows you to make one interface or object work with another that has a different interface. It acts as a bridge, enabling the compatibility of two systems that would not naturally work together. Important Topics for the Adapter Method in JavaScript Design Patterns Use Cases of the A
8 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
Strangler Pattern in Micro-services | System Design
The Strangler pattern is an architectural approach employed during the migration from a monolithic application to a microservices-based architecture. It derives its name from the way a vine slowly strangles a tree, gradually replacing its growth. Similarly, the Strangler pattern involves replacing parts of a monolithic application with microservice
4 min read
SAGA Design Pattern
SAGA pattern is a design pattern that is a long-lived sequence of smaller transactions. This pattern is used to manage and maintain data consistency across multiple microservices. Each transaction is executed by a single service, and the state changes are broadcasted to other services involved in the Saga. It helps to maintain data consistency by p
7 min read
10 Best Python Design Pattern Books for Beginners to Advanced
Imagine you're building different types of furniture using the same basic materials (like wood, screws, and nails). Instead of starting from scratch every time, you create templates or instructions for making specific types of furniture. These templates tell you what pieces to use, how to assemble them, and how to add unique features. In software p
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Article Tags :