Free Lines Arrow
본문 바로가기
Design pattern/GoF(HeadFirst)

[HeadFirst] 커맨드 패턴

by skahn1215 2023. 2. 10.
728x90
반응형

커맨드 패턴

  • 커맨드 패턴을 쓰게 되면 작업을 요청한 곳과 작업을 처리하는 곳을 분리 할 수 있다.
  • 커맨드 패턴에는 명령(command), 수신자(receiver), 발동자(invoker), 클라이언트(client)가 있다.
  • 커맨드 객체는 일련의 행동을 특정 리시버와 연결함으로써 요청을 캡슐화한 것이다.
    밖에서 볼 때는 어떤 객쳬가 리시버 역할을 하는지, 그 리시버가 어떤 일을 하는지 알 수 없습니다
    - 그냥 execute0 메소드를 호출하면 해당 요청이 처리된다는 사실만 알 수 있습니다.

 

커맨드 패턴 수행과정

  • 클라이언트가 커맨드 객체를 생성한다.
    - 커맨드객체에는 행동과 리시버의 정보를 가지고 있다.
  • 클라이언트는 인보커 객체의 setCommand 메소드를 호출한다
    - 이때 커맨드 객체를 같이 넘겨 준다.
  • 인보커에서 커맨드를 수행한다,
    - 커맨드객체에있는 리시버가 가직고 있는 액션을 수행한다.

 

 

커맨드 패턴 다이어 그램

 

커맨드 패턴 예제

Command

public interface Command {
    public void execute();
}

 

Light

public class Light {
    public void on() {
        System.out.println("Light On");
    }
    public void off() {
        System.out.println("Light Off");
    }
}

 

LightOnCommnad

public class LightOnCommand implements Command{
    Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}

 

SimpleRemoteControl

public class SimpleRemoteControl {
    Command slot;

    public SimpleRemoteControl() {
    }

    public void setCommand(Command command) {
        this.slot = command;
    }

    public void pressButton() {
        slot.execute();
    }
}

 

Test

class SimpleRemoteControlTest {
    @Test
    void test() {
        // 클라이언트
        SimpleRemoteControl simpleRemoteControl = new SimpleRemoteControl();
        
        // 커맨드 생성
        Light light = new Light();
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        
        // 커맨드 등록
        simpleRemoteControl.setCommand(lightOnCommand);
        simpleRemoteControl.pressButton();
  }
}

 

 

 

전체 코드:

https://github.com/rnrl1215/design-pattern/tree/main/src/main/java/headfirst/patterns/command

 

GitHub - rnrl1215/design-pattern

Contribute to rnrl1215/design-pattern development by creating an account on GitHub.

github.com

 

 

참고: 

http://www.yes24.com/Product/Goods/108192370

 

헤드 퍼스트 디자인 패턴 - YES24

유지관리가 편리한 객체지향 소프트웨어 만들기!“『헤드 퍼스트 디자인 패턴(개정판)』 한 권이면 충분하다.이유 1. 흥미로운 이야기와 재치 넘치는 구성이 담긴 〈헤드 퍼스트〉 시리즈! 하나

www.yes24.com

 

728x90
반응형

'Design pattern > GoF(HeadFirst)' 카테고리의 다른 글

[HeadFirst] 데코레이터 패턴  (0) 2023.01.07
[HeadFirst] 옵저버 패턴  (0) 2022.12.03

댓글