bartleby
search
close search
Hit Return to see all results

How to implement a pluggable Adapter design pattern in Java?

Question

How to implement a pluggable Adapter design pattern in Java?

check_circleAnswer
Step 1

Let’s say we have a client class called Client.java which calls method1( ) of an existing library class LibM to fulfill a functionality.

fullscreen
Step 2

Let’s say we need the client class Client.java to be able to accomplish the same functionality (printing a message) using another library class LibN. However, the new library class does not have a method named method1( ) but instead has methodA( ) for the same functionality.

fullscreen
Step 3

In order to use the new library class we need to build an adapter class and an adapter interface as follows. Use of the interface class allows plug and play capability. We can interchange the concrte library implementation class without having to make extensive changes to the client class. Also, in future if new library classes need to be used we need to build new adapter classes implementing the same library interface class.

fullscreen
Step 4

Both the adapters implement the Lib_Interface interface which has a method called method1( ). Hence the client class which will use the library concrete implementations will be aware of only the method in the contract Lib_Interface. In the method implementations of the adapter classes the method call to the actual library class is made. In other words, the adapters delegate the method call made by the client to the concrete library class method each of them embed.

fullscreen
Step 5

The implementation demonstrates the pluggability of the adapter approach. The concrete library class to be instantiated and used is known only at runtime. It is passed as an argument at the command line while running the client class. Inside the client class both the library concrete instances are of type Lib_Interface so that run time dynamic binding can be accomplished and the method1( ) can be called on both the concrete implementations. After compiling the classes and the interface, the code is run by as follows at the command line:

>java Client “M”

>java Client “N”

In each case the appropriate library class is called and the message is displayed accordingly.

fullscreen

Stuck on your homework?

Get expertly curated answers to your homework questions for just $9.99/month

Get As ASAP
Tagged in

Engineering

Computer Science

Object Oriented Programming

Sorry about that. What wasn’t helpful?

Find all the answers to your study problems with bartleby.
Textbook solutions plus Q&A. Get As ASAP arrow_forward