Java/Design Pattern

[Design Pattern] Command Pattern

예은파파 2020. 9. 26. 00:15

 

커맨드 패턴( Command Pattern ) 

  • 객체의 행위(메서드)를 클래스로 만들어 캡슐화 하는 패턴.
  • 실행될 기능을 캡슐화함으로써 주어진 여러 기능을 실행할 수 있는 재사용성이 높은 클래스를 설계하는 패턴
  • 이벤트가 발생했을 때 실행될 기능이 다양하면서도 변경이 필요한 경우에 이벤트를 발생시키는 클래스를 변경하지 않고 재사용하고자 할 때 유용하다.

 

Command Pattern 클래스 구조

package CommandPattern;

// 입력된 Command를 실행시키는 클래스
public class Button {

	private Command theCommand;
	
	public Button( Command theCommand ) {
		
		setCommand( theCommand );
	}
	
	public void setCommand( Command newCommand ) {
		
		this.theCommand = newCommand;
	}
	
	public void pressed() {
		
		theCommand.execute();
	}
}

===============================================================================================

package CommandPattern;

// 기능들의 Interface
public interface Command {

	public abstract void execute();
}

===============================================================================================

package CommandPattern;

// Alarm 기능
public class Alarm {

	// Alarm 시작
	public void start() {
		
		System.out.println( "Alarming" );
	}
}

===============================================================================================

package CommandPattern;

// Lamp 기능
public class Lamp {
	
	// Lamp 켜기.
	public void turnOn(){ 
		
		System.out.println("Lamp On"); 
	}
}

 

 

Alarm 과 Lamp 기능들의 Command Interface의 execute 메서드를 구현하는 기능 클래스 생성

( 생성자를 통해 기능을 주입한 뒤, @Override 한 execute 메서드를 구현하여 기능 클래스를 호출한다.

 

 

package CommandPattern;

public class AlarmStartCommand implements Command {

	private Alarm theAlarm;
	
	public AlarmStartCommand( Alarm theAlarm ) {
		
		this.theAlarm = theAlarm;
	}

	@Override
	public void execute() {
		
		theAlarm.start();
	}
}


===============================================================================================

package CommandPattern;

public class LampOnCommand implements Command {

	private Lamp theLamp;
	
	public LampOnCommand( Lamp theLamp ) {
		
		this.theLamp = theLamp;
	}
	
	@Override
	public void execute() {
		
		theLamp.turnOn();
	}

}

 

실제 Client에서 사용하는 예제 

package CommandPattern;

public class Client {

	public static void main(String[] args) {
		
	// Lamp 기능 생성 
	Lamp lamp = new Lamp();
	// Command Interface를 구현한 Lamp 기능 캡슐화
	Command lampOnCommand = new LampOnCommand( lamp );
        
	// Alarm 기능 생성
	Alarm alarm = new Alarm();
	// Command Interface를 구현한 Alarm 기능 캡슐화
	Command alarmStartCommand = new AlarmStartCommand( alarm );

	// 기능을 실행해주는 Button 클래스
	// 생성자를 통해 Command를 주입(Lamp 켜기)
	Button button1 = new Button( lampOnCommand );
	// 실행
	button1.pressed();

	// 생성자를 통해 Command를 주입(Alarm 켜기)
	Button button2 = new Button( alarmStartCommand );
	// 실행
	button2.pressed();
	// button의 기능 변경 (command주입)
	button2.setCommand( lampOnCommand );
	button2.pressed();
    
	}
}

 

실행 결과.

 

'Java > Design Pattern' 카테고리의 다른 글

[Design Pattern] Chain of Responsibility Pattern  (0) 2020.11.23
[Design Pattern] Observer Pattern  (0) 2020.10.02