0% found this document useful (0 votes)
68 views

Adapter Design Pattern: CECS 470 Fall 2017 Mimi Opkins

The adapter pattern allows incompatible interfaces to work together by providing a standard interface for existing classes. An adapter acts as a wrapper that translates requests from one interface to calls that another class can understand. There are two types of adapters - object adapters use composition while class adapters inherit from an existing class. The example shows an audio player using an adapter to play different file formats by passing the appropriate adapter to the player.

Uploaded by

Mudassir niaz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Adapter Design Pattern: CECS 470 Fall 2017 Mimi Opkins

The adapter pattern allows incompatible interfaces to work together by providing a standard interface for existing classes. An adapter acts as a wrapper that translates requests from one interface to calls that another class can understand. There are two types of adapters - object adapters use composition while class adapters inherit from an existing class. The example shows an audio player using an adapter to play different file formats by passing the appropriate adapter to the player.

Uploaded by

Mudassir niaz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Adapter Design Pattern

CECS 470
Fall 2017
Mimi Opkins
Adapter Pattern
• Adapter is a structural design pattern, which allows
incompatible objects to cooperate.
• Adapter acts as a wrapper between two objects, It
catches calls for one object and transforms them to
format and interface recognizable by the second
object.
• In other words, how we put a square peg in a round
hole.
Definition & Applicability

• Adapters are used to enable objects with different interfaces to communicate with each
other.
• The Adapter pattern is used to convert the programming interface of one class into that of
another.
• We use adapters whenever we want unrelated classes to work together in a single program.
• Adapters come in two flavors,
– object adapters and
– class adapters. 
• The concept of an adapter is thus pretty simple; we write a class that has the desired
interface and then make it communicate with the class that has a different interface.
• Adapters in Java can be implemented in two ways:
– by inheritance, and
– by object composition.
Object Adapters

• Object adapters use a compositional technique to adapt one


interface to another.   
• The adapter inherits the target interface that the client expects
to see, while it holds an instance of the adaptee.  
• When the client calls the request() method on its target object
(the adapter), the request is translated into the corresponding
specific request on the adaptee.
• Object adapters enable the client and the adaptee to be
completely decoupled from each other. Only the adapter
knows about both of them.
Example 1
/**
* The SquarePeg class.
* This is the Target class.
*/
public class SquarePeg {
public void insert(String str) {
System.out.println("SquarePeg insert(): " + str);}
}

/**
* The RoundPeg class.
* This is the Adaptee class.
*/
public class RoundPeg {
public void insertIntoHole(String msg) {
System.out.println("RoundPeg insertIntoHole(): " + msg);}
}
Example 1
• If a client only understands the SquarePeg interface
for inserting pegs using the insert() method, how can
it insert round pegs, which are pegs, but that are
inserted differently, using the insertIntoHole()
method?
Example 2
Solution:

Design a RoundToSquarePeg adapter that enables to


insertIntoHole() a RoundPeg object connected to the
adapter to be inserted as a SquarePeg, using insert().
Example 2
/**
* The RoundToSquarePegAdapter class.
* This is the Adapter class.
* It adapts a RoundPeg to a SquarePeg.
* Its interface is that of a SquarePeg.
*/
public class RoundToSquarePegAdapter extends SquarePeg {
private RoundPeg roundPeg;
public RoundToSquarePegAdapter(RoundPeg peg) {
//the roundPeg is plugged into the adapter
this.roundPeg = peg;}
public void insert(String str) {
//the roundPeg can now be inserted in the same manner as a squarePeg!
roundPeg.insertIntoHole(str);}
}
Example 3
// Test program for Pegs.
public class TestPegs {
public static void main(String args[]) {

// Create some pegs.


RoundPeg roundPeg = new RoundPeg();
SquarePeg squarePeg = new SquarePeg();

// Do an insert using the square peg.


squarePeg.insert("Inserting square peg...");

// Now we'd like to do an insert using the round peg.


// But this client only understands the insert()
// method of pegs, not a insertIntoHole() method.
// The solution: create an adapter that adapts
// a square peg to a round peg!

RoundToSquarePegAdapter adapter = new RoundToSquarePegAdapter(roundPeg);


adapter.insert("Inserting round peg...");}
}
Example 3

Execution trace:
SquarePeg insert(): Inserting square peg...
RoundPeg insertIntoHole(): Inserting round peg...
Class Adapters
• Class adapters use multiple interfaces to achieve their goals. 
• As in the object adapter, the class adapter inherits the
interface of the client's target. However, it also inherits the
interface of the adaptee as well.   
• Since Java does not support true multiple inheritance, this
means that one of the interfaces must be inherited from a
Java Interface type. 
• Both of the target or adaptee interfaces could be Java
Interfaces.  
• The request to the target is simply rerouted to the specific
request that was inherited from the adaptee interface.
Consequences of the Adapter Pattern

Class and object adapters have different trade-offs.


A class adapter:
• adapts Adaptee to Target by committing to a concrete Adapter class;
• lets Adapter override some of Adaptee's behavior, since Adapter is a
subclass of Adaptee;
• introduces only one object, and no additional indirection is needed to get to
the adaptee.

An object adapter
• Let’s a single Adapter work with many Adaptees - that is, the Adaptee itself
and all of its subclasses (if any). The Adapter can also add functionality to all
Adaptees at once.
• Makes it harder to override Adaptee behavior. It will require subclassing
Adaptee and making Adapter refer to the subclass rather than the Adaptee
itself.
.

Adapter Pattern – Another Example

• Adapter pattern works as a bridge between two incompatible interfaces. This type
of design pattern comes under structural pattern as this pattern combines the
capability of two independent interfaces.

• This pattern involves a single class which is responsible to join functionalities of


independent or incompatible interfaces. A real life example could be a case of
card reader which acts as an adapter between memory card and a laptop. You
plugin the memory card into card reader and card reader into the laptop so that
memory card can be read via laptop.

• We are demonstrating use of Adapter pattern via following example in which an


audio player device can play mp3 files only and wants to use an advanced audio
player capable of playing vlc and mp4 files.
Implementation

• We have a MediaPlayer interface and a concrete class MP3 implementing


the MediaPlayer interface. MP3 can play mp3 format audio files by default.

• We are having another interface MediaPackage and concrete classes


implementing the MediaPackage interface. These classes can play vlc and
mp4 format files.

• We want to make MP3 to play other formats as well. To attain this, we have
created an adapter class FormatAdapter which implements the MediaPlayer
interface and uses MediaPackage objects to play the required format.

• MP3 uses the adapter class FormatAdapter passing it the desired audio type
without knowing the actual class which can play the desired format. Main,
our demo class will use MP3 class to play various formats.
public interface MediaPlayer { void play(String filename);}
void play(String filename);

Step 1

Create interfaces for MediaPlayer and MediaPackage.

MediaPlayer.java

public interface MediaPlayer {


public void play(String fileName);
}

MediaPackage.java

public interface MediaPackage {


public void playFile(String fileName);
}
Step 2

Create concrete classes implementing the MediaPlayer interface

public class MP3 implements MediaPlayer {


@Override
public void play(String filename) {
System.out.println("Playing MP3 File " + filename);
}
}
Step 3

Create concrete classes implementing the MediaPackage interface.

VlcPlayer.java

public class VlcPlayer implements MediaPackage{


@Override
public void playFile(String fileName) {
System.out.println("Playing vlc file. Name: "+ fileName);
}
}
Step 3

Mp4Player.java

public class Mp4Player implements MediaPackage {

@Override
public void playFile(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
}
}
Step 4
Create adapter class implementing the MediaPlayer interface.

public class FormatAdapter implements MediaPlayer


{ private MediaPackage media;
public FormatAdapter(MediaPackage m) {
media = m;
}
@Override
public void play(String filename) {
System.out.print("Using Adapter --> ");
media.playFile(filename);
}
}
Step 5
Use the MediaPlayer to play different types of audio
formats.
public class Main { public static void main(String[] args) {
MediaPlayer player = new MP3();
player.play("file.mp3");
player = new FormatAdapter(new MP4());
player.play("file.mp4");
player = new FormatAdapter(new VLC());
player.play("file.avi");
}
}
Step 6
Verify the output.
Summary

• When you need to use an existing class and its interface is not
the one you need, use an adapter: allows collaboration
between classes with incompatible interfaces.
• An adapter changes an interface into one a client expects.
• Implementing an adapter may require little work or a great deal
of work depending on the size and complexity of the target
interface.
• There are two forms of adapter patterns: object and class
adapters.
• Class adapters require multiple inheritance.
Credits
• Java Design Patterns - DEPARTMENT OF COMPUTER SCIENCE
AND SOFTWARE ENGINEERING CONCORDIA UNIVERSITY -
Emil Vassev, Joey Paquet : 2006-2012
• Tutorials Point Design Patterns – Adapter Pattern -
https://www.tutorialspoint.com/design_pattern/adapter_
pattern.htm
• Implement the Adapter Design Pattern in Java
https://medium.com/@ssaurel/implement-the-adapter-d
esign-pattern-in-java-f9adb6a8828f

You might also like