Adapter Design Pattern: Mechanism, Java Implementation & Singleton vs Adapter
1. Topic Introduction
Suppose your existing Java application expects every payment gateway or audio player to implement a clean interface (MediaPlayer.play()), yet you just acquired a powerful third-party legacy library whose method names are completely incompatible (AdvancedPlayer.playMp4()). You can't rewrite the third-party library, and rewriting your entire app would be risky. The Adapter Design Pattern solves this incompatibility effortlessly!
When you travel with a laptop whose charger has a flat 2-pin European plug (Adaptee), it simply won't fit into an Indian 3-pin wall socket (Target). Do you break open the wall or throw away your charger? No! You plug a Travel Adapter in between: one side looks like a 3-pin plug to fit the wall (implements Target), and inside it accepts your 2-pin charger (wraps Adaptee) and converts the connection seamlessly!
Target interface expected by the Client and wraps an Adaptee object via composition to translate calls.3. Essential Exam Definitions
Adaptee) into another interface (Target) expected by clients, allowing classes with incompatible interfaces to collaborate without modifying their source code.4. Detailed Technical Explanation & Syntax
1. Four Participants in the Adapter Pattern
Memorize the four standard GoF roles for your exam diagram and explanation:
- 1. Target (Interface): The domain-specific interface the Client understands (
MediaPlayer.play(file)orPaymentProcessor.pay(amount)). - 2. Client: Existing application code collaborating only with objects implementing
Target. - 3. Adaptee: Existing legacy or third-party class with incompatible method signatures (
LegacyMp4Player.renderVideo(path)). - 4. Adapter: Bridge class that
implements Targetand holds a reference toAdaptee(composition), translatingTargetcalls intoAdapteecalls.
2. Object Adapter (Composition) vs Class Adapter (Inheritance)
Object Adapter (preferred in Java!): Adapter implements Target and holds an Adaptee field (has-a composition). Works even if Adaptee is a final class or needs to adapt multiple subclasses.
Class Adapter: Adapter extends Adaptee and implements Target simultaneously (limited in Java because a class can only extend ONE Adaptee class!).
5. Working Principle: Runtime Translation Inside an Object Adapter
- 1. Client calls
player.play("mp4", "lecture.mp4")on aMediaAdapterholdingTargettype. - 2.
MediaAdapterinspects format"mp4"and delegates to its wrappedAdaptee:legacyPlayer.playMp4File("lecture.mp4"). - 3. Client never learns
playMp4Fileexisted—existing client code stays untouched (also obeying Open/Closed Principle!).
6. Examination-Ready Diagrams
Adapter Design Pattern
Structural UML diagram showing how an Adapter wraps an incompatible Adaptee and translates requests from a Target interface expected by the Client.
- Client: Uses objects conforming to the
Targetinterface. - Target (Interface): Expected contract (
MediaPlayer.play()/RoundPlug). - Adapter (Class): Implements
Targetand holds a reference (composition) toAdaptee, translating calls. - Adaptee (Existing Class): Incompatible legacy/third-party class (
AdvancedPlayer.playMp4()).
- Client calls
target.request()on the Adapter. - Adapter converts parameters/method call into Adaptee's interface.
- Adapter delegates execution to
adaptee.specificRequest().
- Draw 4 boxes:
Client--uses--><<interface>> Target<---implements---Adapter---has-a (composition)--->Adaptee. - Inside
Adapter, add a callout note: 'request() { adaptee.specificRequest(); }'.
7. Complete Java Code Examples & Tracing
AdvancedAudioPlayer (Adaptee) so StandardPlayer (Client) can use it seamlessly via MediaPlayer (Target).| 1 | // 1. Target Interface expected by Client |
| 2 | interface MediaPlayer { |
| 3 | void play(String format, String fileName); |
| 4 | } |
| 5 | |
| 6 | // 2. Adaptee (Incompatible third-party/legacy class) |
| 7 | class LegacyVlcEngine { |
| 8 | public void renderVlcStream(String filePath) { |
| 9 | System.out.println("[LegacyVlcEngine] Decoding VLC stream: " + filePath); |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | // 3. Object Adapter: implements Target & wraps Adaptee via composition |
| 14 | class MediaAdapter implements MediaPlayer { |
| 15 | private final LegacyVlcEngine vlcEngine; |
| 16 | |
| 17 | public MediaAdapter(LegacyVlcEngine vlcEngine) { |
| 18 | this.vlcEngine = vlcEngine; |
| 19 | } |
| 20 | |
| 21 | @Override |
| 22 | public void play(String format, String fileName) { |
| 23 | if (format.equalsIgnoreCase("vlc")) { |
| 24 | vlcEngine.renderVlcStream(fileName); // Translates Target -> Adaptee call |
| 25 | } else { |
| 26 | System.out.println("Unsupported format for VLC adapter: " + format); |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // 4. Client using Target interface uniformly |
| 32 | class AudioApp implements MediaPlayer { |
| 33 | private MediaPlayer adapter; |
| 34 | |
| 35 | @Override |
| 36 | public void play(String format, String fileName) { |
| 37 | if (format.equalsIgnoreCase("mp3")) { |
| 38 | System.out.println("[AudioApp] Built-in playback for MP3: " + fileName); |
| 39 | } else if (format.equalsIgnoreCase("vlc")) { |
| 40 | adapter = new MediaAdapter(new LegacyVlcEngine()); |
| 41 | adapter.play(format, fileName); |
| 42 | } else { |
| 43 | System.out.println("Format not supported: " + format); |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | public class AdapterPatternDemo { |
| 49 | public static void main(String[] args) { |
| 50 | MediaPlayer app = new AudioApp(); |
| 51 | app.play("mp3", "revision_audio.mp3"); |
| 52 | app.play("vlc", "ktu_module3_video.vlc"); |
| 53 | } |
| 54 | } |
[AudioApp] Built-in playback for MP3: revision_audio.mp3 [LegacyVlcEngine] Decoding VLC stream: ktu_module3_video.vlc
interfaceimplementsprivate@Override- Modifying the
Adapteesource code directly instead of introducing an Adapter (violates Adapter's core purpose when Adaptee is third-party/legacy!). - Forgetting to label the 4 participants (
Client,Target,Adapter,Adaptee) in exam UML diagrams.
Comparison Tables
| Comparison Basis | Singleton Pattern | Adapter Pattern |
|---|---|---|
| Pattern Category | Creational Pattern (controls object creation) | Structural Pattern (bridges incompatible interfaces) |
| Core Problem Solved | Ensures only ONE shared instance exists globally | Makes two incompatible interfaces work together |
| Key Mechanism | private constructor + private static field + getInstance() | Adapter implements Target & wraps Adaptee via composition |
| Real-World Analogy | One Principal's office / shared printer spooler | 2-pin to 3-pin electrical travel adapter |
| JDK Example | java.lang.Runtime.getRuntime() | java.io.InputStreamReader (adapts InputStream to Reader), Arrays.asList() |
Advantages
- Enables integrating legacy or third-party libraries without altering existing client or adaptee code (supports Open/Closed Principle).
- Separates interface conversion logic cleanly from core business logic (Single Responsibility).
Limitations / Disadvantages
- Adds extra indirection classes, slightly increasing overall codebase complexity when simple refactoring was possible.
Real-World Applications
java.io.InputStreamReaderadapts byte streams (InputStream) into character streams (Reader).- Integrating legacy XML/SOAP banking gateways into modern unified Java
PaymentProcessorinterfaces, and SwingWindowAdapter(related convenience adapter concept).
Important KTU Exam Points
- Draw Diagram 12 labeling
Client -> Target <- Adapter -> Adapteeexplicitly. - Highlight why Object Adapter (composition) is preferred in Java over Class Adapter (inheritance).
Memory Techniques & Revision
- Adapter Roles — 'C-T-A-A': Client talks to Target; Adapter translates to Adaptee.
Common Pitfalls to Avoid
- Confusing the Adapter design pattern with Swing
WindowAdapter(Swing adapters provide empty default methods of a multi-method listener interface, whereas GoF Adapter translates between two incompatible interfaces!).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: The Adapter pattern is a Structural GoF design pattern that enables objects with incompatible interfaces to work together by wrapping an existing class inside a translator implementing the expected target interface.
- Participants: (1)
ClientexpectsTarget; (2)Targetdefines desired interface; (3)Adapteecontains existing incompatible API; (4)AdapterimplementsTargetand holds a reference toAdaptee(composition). - Working: When Client invokes
target.play(), the Adapter translates the request and delegates toadaptee.renderVlcStream()without modifying either Client or Adaptee.
Client -> Target <---implements--- Adapter ---has-a---> Adaptee) and include MediaPlayer/MediaAdapter/LegacyVlcEngine code.Quick Understanding Check
1. Why is Object Adapter (using composition) generally preferred over Class Adapter in Java?