Skip to content
-
Adapter Design Pattern in Java
Last Updated :
02 Dec, 2024
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 JavaImportant Topics for Adapter Design Pattern in Java
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.

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);
}
}
OutputLegacy 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?
- 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.
- 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.
- 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.
- 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.
- 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?
- 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.
- 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.
- 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.
- 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.
- 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.
`;
$(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");
}