Friday, 1 November 2013

Adapter Design pattern - Real Time Example (Mobile Charger)

🚀 Enjoying Java Tutorials?

Subscribe to Ram N Java for clean, beginner-friendly core Java tutorials and interview prep!

🔔 Subscribe to Ram N Java

Introduction

The Adapter Design Pattern is a structural pattern whose core purpose is to enable two incompatible interfaces to work together smoothly. Before writing code, the best way to understand the need for this pattern is by looking at an intuitive real-world scenario that everyone encounters daily: charging a mobile phone using an electric wall socket.

The Incompatibility Problem

Consider the two physical devices involved in charging a phone:

  • Electric Wall Socket: Supplies high alternating current voltage (e.g., 220V or 120V).
  • Mobile Phone: Requires a low direct current voltage (typically 9V or 5V) to charge safely without damaging its battery.

These two entities have completely incompatible interfaces and expectations. You cannot directly plug a smartphone into a 220V wall socket without an intermediate converter.

The Mobile Charger as an Adapter

To make these two incompatible components communicate, we introduce an intermediary: the Mobile Phone Charger.

  • One end of the charger connects to the wall socket and accepts 220V input.
  • The internal adapter circuitry converts high voltage (220V) down to the required low voltage (9V).
  • The other end connects to the mobile phone and supplies the safe 9V output needed for charging.

In this scenario, the mobile phone charger serves as the exact physical equivalent of an Adapter in software design.

Adapter Pattern Role Mapping

Pattern Role Real-World Component Description
Client Mobile Phone Requires 9V power to charge
Target Interface 9V Power Interface The low-voltage power supply expected by the phone
Adaptee Electric Wall Socket Existing provider delivering 220V power
Adapter Mobile Phone Charger Converts 220V into 9V to bridge the two interfaces

Related Tutorials from Ram N Java


Click here to watch in Youtube : https://www.youtube.com/watch?v=0wHsiKriiHo

Click the below Image to Enlarge
Adapter Design pattern - Real Time Example (Mobile Charger)

No comments:

Post a Comment

Tutorials