*content
명령 혹은 요청 자체를 캡슐화하는 패턴
Command
abstract class Command {
protected Robot robot;
public void setRobot (Robot _robot){
this.robot = _robot;
}
public abstract void execute();
}
class MoveForwardCommand extends Command{
int space;
public MoveForwardCommand (int _space){
space = _space;
}
public void execute() {
robot.moveForward(space);
}
}
class TurnCommand extends Command{
Robot.Direction derection;
public TurnCommand (Robot.Direction _direction){
direction = _direction;
}
public void execute() {
robot.turn(direction);
}
}
class PickupCommand extends Command{
public void execute() {
robot.pickup();
}
}
Robot
public class Robot{
public enum Direction {LEFT, RIGHT}
public void moveForward(int space){
System.out.println(space + "칸 전진");
}
public void turn(Direction _direction){
System.out.println(
(_direction == Direction.LEFT?"왼쪽":"오른쪽")
+ "으로 방향 전환");
}
public void pickup() {
System.out.println("물건 집어들기");
}
}
RobotKit
public class RobotKit {
private Robot robot = new Robot();
private ArrayList<Command> commands new ArrayList<Command>();
public void addCommand (Command command){
commands.add(command);
}
public void start() {
for (Command command : commands){
command.setRobot(robot);
command.execute();
}
}