Design Patterns Adapter Pattern
Design Patterns Adapter Pattern
1 of 5
http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
Advertisements
Previous Page
Next Page
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.
We
have
MediaPlayer
interface
and
concrete
class
classes
implementing
the
and
AdvancedMediaPlayer
interface. These classes can play vlc and mp4 format files.
We want to make AudioPlayer to play other formats as well. To
attain this, we have created an adapter class MediaAdapter
which
implements
the
MediaPlayer
interface
and
uses
03/08/2016 14:15
2 of 5
http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
AdvancedMediaPlayer.java
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
Mp4Player.java
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file. Name: "+ fileName);
03/08/2016 14:15
3 of 5
http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
}
}
03/08/2016 14:15
4 of 5
http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
AdapterPatternDemo.java
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3",
audioPlayer.play("mp4",
audioPlayer.play("vlc",
audioPlayer.play("avi",
}
}
Previous Page
PDF
Next Page
Advertisements
03/08/2016 14:15
5 of 5
http://www.tutorialspoint.com/design_pattern/adapter_pattern.htm
03/08/2016 14:15