전기차충전기
[디자인패턴] 커멘드(Command)
hyeok0724.kim@gmail.com
2022. 5. 25. 20:57
반응형
작성일: 22년 5월 25일
Index
1. 배경
2. Robot 코드
3. Command 코드
4. RobotKit 코드
5. Main 코드
1. 배경
- 로봇에게 명령어를 주면 순서대로 수행함
2. 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("앞의 물건 집어들기");
}
}
3. 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 direction;
public TurnCommand (Robot.Direction _direction){
direction = _direction;
}
public void execute(){
robot.turn(direction);
}
}
class PickupCommand extends Command {
public void execute(){
robot.pickup();
}
}
4. 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();
}
}
}
5. Main 코드
RobotKit robotKit = new RobotKit();
robotKit.addCommand(new MoveForwardCommand(2));
robotKit.addCommand(new TurnCommand(Robot.Direction.LEFT));
robotKit.addCommand(new MoveForwardCommand(1));
robotKit.addCommand(new TurnCommand(Robot.Direction.RIGHT));
robotKit.addCommand(new PickupCommand());
robotKit.start();
Referece:
https://www.youtube.com/watch?v=lJES5TQTTWE&t=564s
반응형