Skip to content

Instantly share code, notes, and snippets.

@marc-x-andre
Created November 9, 2017 14:27
Show Gist options
  • Save marc-x-andre/486cc044779bfa3d13c654b460d6fa3f to your computer and use it in GitHub Desktop.
Save marc-x-andre/486cc044779bfa3d13c654b460d6fa3f to your computer and use it in GitHub Desktop.
Java Command (Design Pattern) [French/Français]
Java Command (Design Pattern) [French/Français]
public interface Command {
void execute();
}
public class Faxe implements Command {
private String tel;
public Faxe(String tel) {
this.tel = tel;
}
public void execute() {
System.out.println("Document faxe au numero : "+tel+".");
}
}
import java.util.ArrayList;
import java.util.List;
public class Imprimante {
private List<Command> history = new ArrayList<Command>();
public void addCommand(Command command) {
history.add(command);
command.execute();
}
/**
* Historique optionnel dans le design pattern 'command'
*/
public void printHistory() {
System.out.println("__HISTORIQUE__");
for (Command command : history) {
System.out.println(command.getClass().getName());
}
}
}
public class Imprime implements Command {
private String document;
public Imprime(String document) {
this.document = document;
}
public void execute() {
System.out.println("Impression du document "+document+".");
}
}
public class Main {
public static void main(String... args) {
Imprimante imprimante = new Imprimante();
Command imprime = new Imprime("test.pdf");
Command scanner = new Scanner();
Command faxe = new Faxe("514-123-4321");
imprimante.addCommand(imprime);
imprimante.addCommand(scanner);
imprimante.addCommand(faxe);
System.out.print("\n\n");
imprimante.printHistory();
}
}
public class Scanner implements Command {
public void execute() {
System.out.println("Scanning en cours... ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment