Sample bartleby Q&A Solution
You ask questions, our tutors answer
Browse
Question

How to implement a pluggable Adapter design pattern in Java?

Expert Answer

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

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.

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.

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.

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.