특정 기능들을 캡슐화 시키는 패턴이다. 그래서 매개변수를 이용하여 기능에 다른 요구사항들을 넣을 수 있게된다.
Invoker : 호출자
Receiver : 수신자
Command : 명령
위와 같은 객체로 구분된다.
인보커는 기능의 실행을 요청하고 리시버는 명령을 수행하는 객체다.
커맨드 객체들은 모두 같은 인터페이스 아래서 구현되어야 한다.
그 중심을 잡아주는 인터페이스가 바로 커맨드 인터페이스다.
많은 예제들에서 인터페이스를 활용하지만, 여기서는 추상클래스를 가지고 구현해보겠다.
package command;
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("옆의 물건 집어들기");
}
}
package 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 MoveFowardCommand ( int _space )
{
space = _space;
}
public void execute()
{
robot.MoveForward(space);
}
}
class TurnCommand extends Command
{
Robot.Direction direction;
public TurnCommand ( Robot.Direction _direction
{
direction = _direction;
}
public void execute ()
{
robot.turn(direction);
}
}
class PickupCommand extends Command
{
public void execute()
{
robot.pickup();
}
}
package command;
import java.util.ArrayList;
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();
}
}
}