Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created June 18, 2016 15:15
Show Gist options
  • Save mitulmanish/136d2cdae9358ec6988365962a08e6c2 to your computer and use it in GitHub Desktop.
Save mitulmanish/136d2cdae9358ec6988365962a08e6c2 to your computer and use it in GitHub Desktop.
Command Pattern implemented in Java
interface DoorCommand {
String execute();
}
class Door {
String doorName;
public Door(String doorName) {
this.doorName = doorName;
}
@Override
public String toString() {
return doorName;
}
}
class OpenCommand implements DoorCommand {
Door door;
public OpenCommand(Door door) {
this.door = door;
}
@Override
public String execute() {
return "Opened " + door;
}
}
class CloseCommand implements DoorCommand {
Door door;
public CloseCommand(Door door) {
this.door = door;
}
@Override
public String execute() {
return "Closed " + door;
}
}
class HAL9000DoorsOperations {
DoorCommand openCommand;
DoorCommand closeCommand;
public HAL9000DoorsOperations(Door door) {
openCommand = new OpenCommand(door);
closeCommand = new CloseCommand(door);
}
public String open() {
return openCommand.execute();
}
public String close() {
return closeCommand.execute();
}
}
public class Main {
public static void main(String[] args) {
// write your code here
HAL9000DoorsOperations doorOperation = new HAL9000DoorsOperations(new Door("Steel Door"));
System.out.println(doorOperation.open());
System.out.print(doorOperation.close());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment