23.2.2022
Command Pattern
Description
The command pattern is used to abstract function calls. It is particularly well suited to execute e.g. configuration files, which can then form more complex algorithms. Here a series of commands is read and executed in order.
Another application example is to execute interactions in a program, to store and if necessary also again to revert.
UML
Code
interface Command {
public void exec();
}
class ActionMovie {
String name;
public ActionMovie(String name) {
this.name = name;
}
public void playActionMovie() {
System.out.println("play: " + this.name);
}
}
class HorrorMovie {
String name;
public HorrorMovie(String name) {
this.name = name;
}
public void playHorrorMovie() {
System.out.println("play: " + this.name);
}
}
class PlayActionVideo implements Command {
ActionMovie movie;
public PlayActionVideo(ActionMovie movie) {
this.movie = movie;
}
@Override
public void exec() {
movie.playActionMovie();
}
}
class PlayHorrorVideo implements Command {
HorrorMovie movie;
public PlayHorrorVideo(ActionMovie movie) {
this.movie = movie;
}
@Override
public void exec() {
movie.playHorrorMovie();
}
}
class MoviePlayer {
List<Command> playlist = new ArrayList<>();
public void startPlaylist() {
playlist.forEach(Command::exec);
}
}
Standort Hannover
newcubator GmbH
Bödekerstraße 22
30161 Hannover
Standort Dortmund
newcubator GmbH
Westenhellweg 85-89
44137 Dortmund