Definition
- defines a family of algorithms,
- encapsulates each algorithm, and
- makes the algorithms interchangeable within that family
When to Use?
- To choose an appropriate algorithm/behavior at run time when there are multiple algorithms/behaviors executing the same task/operation.
UML
Real World Scenario
As depicted in the UML diagram below, we have an application that plays audio files. And we have many options to play the audio files: VLC Media Player, Window Media Player, KMPlayer. Now, the client or the main program will choose which media player to play the audio files at run time.
Code Sample
MainProgram.java
import java.io.File;
public class MainProgram {
public static void main(String[] args) {
File mediaFile = new File("audio.mp3");
MediaPlayer player = new MediaPlayer(new VLCMediaPlayer());
// MediaPlayer player = new MediaPlayer(new WindowMediaPlayer());
// MediaPlayer player = new MediaPlayer(new KMPlayer());
player.play(mediaFile);
}
}MediaPlayer.java
import java.io.File;
public class MediaPlayer {
private IPlayer player;
public MediaPlayer(IPlayer player) {
this.player = player;
}
public void play(File mediaFile) {
player.play(mediaFile);
}
}IPlayer.java
import java.io.File;
public interface IPlayer {
public void play(File mediaFile);
}
VLCMediaPlayer.java
import java.io.File;
public class VLCMediaPlayer implements IPlayer {
@Override
public void play(File file) {
System.out.println("Playing via.
VLC Media Player");
}
}WindowMediaPlayer.java
import java.io.File;
public class WindowMediaPlayer implements IPlayer {
@Override
public void play(File file) {
System.out.println("Playing via.
Window Media Player");
}
}KMPlayer.java
import java.io.File;
public class KMPlayer implements IPlayer {
@Override
public void play(File file) {
System.out.println("Playing via.
KMPLayer");
}
}
No comments :
Post a Comment