본문 바로가기

OOP/디자인 패턴

Command 패턴

1. command 패턴이란?

명령(command), 수신자(receiver), 발동자(invoker)의 역할이 중요한 패턴이다.

큰 흐름을 보면 각 명령을 발동자에게 전달하고 발동자는 전달받은 명령을 수신자가 수행할 수 있도록 하는 구조이다.

그래서 예로 들어 로봇에게 명령을 내린다고 생각하자.

1. 로봇에게 내려질 각 명령을 만든다

2. 로봇의 명령을 담을 RobotKit ( invoker)를 만든다.

3. RobotKit은 각 명령을 Robot ( receiver ) 가 실행할 수 있도록 한다.

 

command 패턴을 사용하면 실행할 명령들을 순차적으로 다 담아서 한번에 명령할 수 있다는 장점이 있다.

 

2. receiver

class Robot {
    enum class Direction { LEFT, RIGHT }
    fun moveForward (space : Int){
        Log.e("Robot","${space}칸 전진")
    }
    fun turn(_direction : Direction){
        var result = ""
        result = if(_direction==Direction.LEFT){
            "왼쪽"
        }else{
            "오른쪽"
        }
        Log.e("Robot","${result}으로 방향 전환")
    }
    fun pickup(){
        Log.e("Robot","물건 집어 들기")
    }
}

 

3. command 

abstract class Command {
    lateinit var robot : Robot
    abstract fun execute()
}


class MoveForwardCommand(_space : Int) : Command() {
    var space = _space
    override fun execute() {
        robot.moveForward(space)
    }
}

class TurnCommand(_direction : Robot.Direction) : Command(){
    var direction  = _direction
    override fun execute() {
        robot.turn(direction)
    }
}

class PickupCommand : Command(){
    override fun execute() {
        robot.pickup()
    }
}

 

4. invoker

class RobotKit {
    private val robot : Robot = Robot()
    private val commands : MutableList<Command> = mutableListOf()
    fun addCommand(_command: Command){
        commands.add(_command)
    }
    fun start(){
        for (command in commands){
            command.robot = robot
            command.execute()
        }
    }
}

 

5. main 

class MainActivity() : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val robotKit = RobotKit()
        robotKit.addCommand(MoveForwardCommand(2))
        robotKit.addCommand(TurnCommand(Robot.Direction.LEFT))
        robotKit.addCommand(MoveForwardCommand(5))
        robotKit.addCommand(TurnCommand(Robot.Direction.RIGHT))
        robotKit.addCommand(PickupCommand())
        robotKit.start()
    }
}

'OOP > 디자인 패턴' 카테고리의 다른 글

Facade 패턴  (0) 2021.06.28
Proxy 패턴  (0) 2021.06.27
Adapter 패턴  (0) 2021.06.26
State 패턴  (0) 2021.06.22
Strategy ( 전략 패턴 )  (0) 2021.06.16