Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Adapter Design Pattern
Next article icon

Adapter Design Pattern in Java

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Adapter Design Pattern in Java acts as a bridge between two incompatible interfaces, allowing them to work together. It is commonly used when you want to integrate a legacy system or third-party library with your application without modifying their code. This pattern promotes reusability and flexibility. In this article, we’ll explore its concept, benefits, and implementation in Java.

Adapter-Design-Pattern-in-Java
Adapter Design Pattern in Java

Important Topics for Adapter Design Pattern in Java

  • What is Adapter Design Pattern in Java?
  • Components of Adapter Design Pattern in Java
  • Adapter Design Pattern Example in Java
  • How Adapter Design Pattern works?
  • Why do we need Adapter Design Pattern?
  • When not to use Adapter Design Pattern?

What is Adapter Design Pattern in Java?

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.

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 in Java

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 in Java

Below is the problem statement to Understand Adapter Design Pattern in Java:

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.

Java
// Target Interface
public interface Printer {
    void print();
}

2. Adaptee (LegacyPrinter)

The existing class with an incompatible interface.

Java
// Adaptee
public class LegacyPrinter {
    public void printDocument() {
        System.out.println("Legacy Printer is printing a document.");
    }
}

3. Adapter (PrinterAdapter)

The class that adapts the LegacyPrinter to the Printer interface.

Java
// 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.

Java
// Client Code
public class Client {
    public static void clientCode(Printer printer) {
        printer.print();
    }
}

Complete Code for the above example in Java:

Java
// Target Interface
interface Printer {
    void print();
}

// Adaptee
class LegacyPrinter {
    public void printDocument() {
        System.out.println("Legacy Printer is printing a document.");
    }
}

// Adapter
class PrinterAdapter implements Printer {
    private LegacyPrinter legacyPrinter;

    public PrinterAdapter() {
        this.legacyPrinter = new LegacyPrinter();
    }

    @Override
    public void print() {
        legacyPrinter.printDocument();
    }
}

// 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);
    }
}

Output
Legacy Printer is printing a document.

How Adapter Design Pattern works?

  • Client Request: The client initiates a request by calling a method on the adapter using the target interface.
  • Adapter Translation: The adapter translates or maps the client's request into a form that the adaptee understands, using the adaptee's interface.
  • Adaptee Execution: The adaptee performs the actual work based on the translated request from the adapter.
  • 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 lot of adapters for various components, and the complexity of managing these adapters becomes difficult.
    • 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.



Next Article
Adapter Design Pattern

S

sanketsay9qs
Improve
Article Tags :
  • Design Pattern
  • System Design
  • Java Design Patterns

Similar Reads

    Adapter Design Pattern
    One structural design pattern that enables the usage of an existing class's interface as an additional interface is the adapter design pattern. To make two incompatible interfaces function together, it serves as a bridge. This pattern involves a single class, the adapter, responsible for joining fun
    8 min read
    Composite Design Pattern in Java
    The Composite Design Pattern is a structural design pattern that lets you compose objects into tree-like structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. In other words, whether dealing with a single object or a grou
    8 min read
    Decorator Method Design Pattern in Java
    A structural design pattern called the Decorator Design Pattern enables the dynamic addition of functionality to specific objects without changing the behavior of other objects in the same class. To wrap concrete components, a collection of decorator classes must be created. Decorator Method Design
    10 min read
    Bridge Method Design Pattern in Java
    The Bridge Design Pattern is a structural design pattern that decouples an abstraction from its implementation so that the two can vary independently. This pattern is useful when both the abstractions and their implementations should be extensible by subclassing. The Bridge pattern allows us to avoi
    6 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-
    6 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 Metho
    8 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences