ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 3. 커맨드 패턴(Command Pattern)
    디자인패턴 2021. 12. 20. 17:42

    커맨드 패턴이란?

    이벤트가 발생했을 때 실행될 기능이 다양하면서도 변경이 필요한 경우에 이벤트를 발생시키는 클래스를 변경하지 않고 재사용하고자 할 때 유용하다. 커맨드 패턴은 실행될 기능을 캡슐화 함으로써 기능의 실행을 요구하는 호출자 클래스와 실제 기능을 실행하는 수신자 클래스 사이의 의존성을 제거한다. 따라서 실행될 기능의 변경에도 호출자 클래스를 수정 없이 그대로 사용할 수 있도록 해준다.

     

     


     

    아래 예제를 보면서 이해해보자

    버튼을 누르는 동작에 따라 다른 기능을 실행하는 예제
    //램프 클래스
    public class Lamp {
    	public void turnOn() {
        	System.out.println("Lamp On");
        }
    }
    
    //알람 클래스
    public class Alarm {
    	public void start() {
        	System.out.println("Alarming...");
        }
    }
    
    //enum
    enum Mode { LAMP, ALARM };
    
    //버튼 클래스
    public class Button {
    	private Lamp theLamp;
        private Alarm theAlarm;
        private Mode theMode;
        
        public Button(Lamp theLamp, Alarm theAlarm) {
        	this.theLamp = theLamp;
            this.theAlarm = theAlarm;
        }
        
        public Button(Mode mode) { //램프모드 또는 알람모드를 설정함
        	this.theMode = mode;
        }
        
        public void pressed() { //설정된 모드에 따라 램프를 켜거나 알람을 울림
        	switch(theMode) {
            	case LAMP: //램프 모드면 램프를 켬
                	theLamp.turnOn();
                	break;
                case ALARM: //알람 모드면 알람을 울리게 함
                	theAlarm.start();
                	break;
            }
        }
    }
    
    //클라이언트 클래스
    public class Client {
    	public static void main(String[] args) {
        	Lamp lamp = new Lamp();
            Alarm alarm = new Alarm();
            Button button = new Button(lamp, alarm);
            
            button.setMode(Mode.LAMP);
            button.pressed(); //램프모드를 설정했으므로 램프가 켜짐
            
            button.setMode(Mode.ALARM);
            button.pressed(); //알람모드를 설정했으므로 아람이 울림
        }
    }

     

    위의 예제는 버튼을 눌렀을 때의 기능을 변경하려면 다시 Button 클래스의 코드를 수정해야한다.

    해당 코드에 커맨드 패턴을 적용하면 Button 클래스를 수정없이 다양한 기능을 추가할 수 있다.

    아래 예제처럼 코드를 수정해보자.

     

    램프를 켜는 기능과 끄는 기능을 가질 수 있는 버튼 예제
    //커맨드 인터페이스
    public interface Command {
    	public abstract void execute();
    }
    
    //버튼 클래스
    public class Button {
    	private Command theCommand;
        
        public Button(Command theCommand) {
        	setCommand(theCommand);
        }
        
        public void setCommand(Command newCommand) {
        	this.theCommand = newCommand;
        }
        
        public void pressed() { //버튼이 눌리면 주어진 Command의 execute 메서드를 호출함
        	theCommand.execute();
        }
    }
    
    //램프 클래스
    public class Lamp {
    	public void turnOn() {
        	System.out.println("Lamp On");
        }
        
        public void turnOff() {
        	System.out.println("Lamp Off");
        }
    }
    
    //램프 켜는 커맨드 클래스
    public class LampOnCommand implements Command {
    	private Lamp theLamp;
        
        public LampOnCommand(Lamp lamp) {
        	this.theLamp = theLamp;
        }
        
        public void execute() {
        	theLamp.turnOn();
        }
    }
    
    //램프 끄는 커맨드 클래스
    public class LampOffCommand implements Command {
    	private Lamp theLamp;
        
        public LampOffCommand(Lamp lamp) {
        	this.theLamp = theLamp;
        }
        
        public void execute() {
        	theLamp.turnOff();
        }
    }
    
    //클라이언트 클래스
    public class Client {
    	public static void main(String[] args) {
        	Lamp lamp = new Lamp();
            Command lampOnCommand = new LampOnCommand(lamp);
            Command lampOffCommand = new LampOffCommand(lamp);
            
            Button button = new Button(lampOnCommand); //램프를 켜는 커맨드를 설정함
            button.pressed(); //버튼을 누르면 램프가 켜짐
            
            Button button = new Button(lampOffCommand); //램프를 끄는 커맨드를 설정함
            button.pressed(); //버튼을 누르면 램프가 꺼짐
        }
    }

     

     

     


     

     

    해당 포스트는 JAVA 객체지향 디자인패턴을 읽은 후 기록한 내용입니다.

    참고서적링크 : https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=38792551

     

    자바 객체지향 디자인 패턴

    체계적인 학습법을 바탕으로 설명하는 객체지향 디자인 패턴의 교과서. 자바와 UML을 중심으로 객체지향 이론이 무엇인지를 배운 다음 GoF에서 소개하는 디자인 패턴의 핵심 10가지를 알기 쉽게

    www.aladin.co.kr

    이미지 아이콘 출처: https://www.flaticon.com/free-icon/pattern-lock_4643427?term=pattern&related_id=4643427

Designed by Tistory.