KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 4: Introduction to Design Patterns

Adapter Design Pattern: Mechanism, Java Implementation & Singleton vs Adapter

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Adapter design patternAdapter working mechanismAdapter implementation in JavaReal-world examplesSingleton versus Adapter where relevant

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!

2. Start From Zero: Travel Power Socket Adapter (2-Pin European Plug -> 3-Pin Indian Socket)

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!

Key Takeaway: Adapter is a Structural pattern that bridges two incompatible interfaces: it implements the Target interface expected by the Client and wraps an Adaptee object via composition to translate calls.

3. Essential Exam Definitions

Adapter Design Pattern
A Structural design pattern that converts the interface of an existing class (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) or PaymentProcessor.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 Target and holds a reference to Adaptee (composition), translating Target calls into Adaptee calls.

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. 1. Client calls player.play("mp4", "lecture.mp4") on a MediaAdapter holding Target type.
  2. 2. MediaAdapter inspects format "mp4" and delegates to its wrapped Adaptee: legacyPlayer.playMp4File("lecture.mp4").
  3. 3. Client never learns playMp4File existed—existing client code stays untouched (also obeying Open/Closed Principle!).

6. Examination-Ready Diagrams

Diagram 12

Adapter Design Pattern

ClientExpects Target<<interface>> Targetplay(type, file)Adapterimplements Target + translatesAdapteeIncompatible APIAdapter wraps Adaptee (has-a) and exposes Target interface to Client

Structural UML diagram showing how an Adapter wraps an incompatible Adaptee and translates requests from a Target interface expected by the Client.

Key Components
  • Client: Uses objects conforming to the Target interface.
  • Target (Interface): Expected contract (MediaPlayer.play() / RoundPlug).
  • Adapter (Class): Implements Target and holds a reference (composition) to Adaptee, translating calls.
  • Adaptee (Existing Class): Incompatible legacy/third-party class (AdvancedPlayer.playMp4()).
Step-by-Step Flow
  1. Client calls target.request() on the Adapter.
  2. Adapter converts parameters/method call into Adaptee's interface.
  3. Adapter delegates execution to adaptee.specificRequest().
How to Draw in KTU Exam
  • 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

Object Adapter Pattern Implementation (`MediaPlayer` -> `AdvancedMediaPlayer`)AdapterPatternDemo.java
Classic Java Adapter example adapting an incompatible AdvancedAudioPlayer (Adaptee) so StandardPlayer (Client) can use it seamlessly via MediaPlayer (Target).
1// 1. Target Interface expected by Client
2interface MediaPlayer {
3 void play(String format, String fileName);
4}
5
6// 2. Adaptee (Incompatible third-party/legacy class)
7class 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
14class 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
32class 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
48public 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}
Expected Output
[AudioApp] Built-in playback for MP3: revision_audio.mp3
[LegacyVlcEngine] Decoding VLC stream: ktu_module3_video.vlc
Keywords:interfaceimplementsprivate@Override
Common Exam & Coding Mistakes
  • Modifying the Adaptee source 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

Singleton vs Adapter Design Pattern
Comparison BasisSingleton PatternAdapter Pattern
Pattern CategoryCreational Pattern (controls object creation)Structural Pattern (bridges incompatible interfaces)
Core Problem SolvedEnsures only ONE shared instance exists globallyMakes two incompatible interfaces work together
Key Mechanismprivate constructor + private static field + getInstance()Adapter implements Target & wraps Adaptee via composition
Real-World AnalogyOne Principal's office / shared printer spooler2-pin to 3-pin electrical travel adapter
JDK Examplejava.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.InputStreamReader adapts byte streams (InputStream) into character streams (Reader).
  • Integrating legacy XML/SOAP banking gateways into modern unified Java PaymentProcessor interfaces, and Swing WindowAdapter (related convenience adapter concept).

Important KTU Exam Points

  • Draw Diagram 12 labeling Client -> Target <- Adapter -> Adaptee explicitly.
  • 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) Client expects Target; (2) Target defines desired interface; (3) Adaptee contains existing incompatible API; (4) Adapter implements Target and holds a reference to Adaptee (composition).
  • Working: When Client invokes target.play(), the Adapter translates the request and delegates to adaptee.renderVlcStream() without modifying either Client or Adaptee.
Exam Diagram Note: Draw Diagram 12 (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?