디자인 패턴 - Command패턴

jodbsgh·2022년 6월 19일
0

🎨"디자인 패턴"

목록 보기
4/4

😀Command패턴이란

특정 기능들을 캡슐화 시키는 패턴이다. 그래서 매개변수를 이용하여 기능에 다른 요구사항들을 넣을 수 있게된다.

🛒Command패턴의 구성

Invoker : 호출자
Receiver : 수신자
Command : 명령
위와 같은 객체로 구분된다.

인보커는 기능의 실행을 요청하고 리시버는 명령을 수행하는 객체다.

🧐Command패턴을 사용하는 이유

  1. 인보커와 리시버, 커맨드가 각각 캡슐화 되어서 결합도가 낮아진다.

🤔Command패턴의 문제점

  1. 리시버 객체의 동작이 늘어날 때 마다 커맨드 클래스가 늘어나기 때문에 관리할 클래스가 많아진다.

🎨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();
        }
    }
}
profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글