Created
June 18, 2016 15:15
-
-
Save mitulmanish/136d2cdae9358ec6988365962a08e6c2 to your computer and use it in GitHub Desktop.
Command Pattern implemented in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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