3. 다음과 같은 리모콘의 S/W제작을 의뢰 받았습니다.
에어컨
TV
오디오
현관문
거실 등
4. 기능은 간단합니다.
에어컨
TV
오디오
현관문
거실 등 1. 휠을 통한 가전제품 선택
2. 버튼을 통한 On/Off
5. 먼저, 가전제품과 직접적으로 연결하기로 합니다.
에어컨
TV
오디오
현관문
거실 등
public void airconButtonClick(Aircon aircon) {
if(aircon.isOn()) {
aircon.off();
} else {
aircon.on();
}
}
6. 먼저, 가전제품과 직접적으로 연결하기로 합니다.
에어컨
TV
오디오
현관문
거실 등
public void audioButtonClick(Audio audio) {
if(audio.isPlay()) {
audio.stop();
} else {
audio.play();
}
}
7. 하다보니까…
TV
오디오
현관문
거실등
???
public void ???ButtonClick(??? ???) {
if(???()) {
???();
} else {
???();
}
}
가전제품마다 메소드가 달라,
새로운 기능이 추가되면,
매번 추가해 주어야 합니다.
8. !
그래서…
하나의 메소드로, 여러 가전제품을 조작 할 수 없을까?
remote.buttonClick();
remote.tvButtonClick();
remote.audioButtonClick();
remote.???ButtonClick();
9. !
그래서 Command Pattern!
요구사항을 객체로 캡슐화합니다.
public interface Command {
public void execute();
}
10. 먼저, 가전제품 별로 Command객체를 구현합니다.
에어컨
TV
오디오
현관문
거실 등
public class AirconCommand implements Command {
Aircon aircon;
public airconCommand (Aircon aircon) {
this.aircon = aircon;
}
!
@Override
public void execute() {
if(aircon.isOn()) {
aircon.off();
} else {
aircon.on();
}
}
}
11. 다시 기능을 볼까요?
에어컨
TV
오디오
현관문
거실 등
1. 휠을 통한 가전제품 선택
!
!
2. 버튼을 통한 On/Off
Command객체를 Remote객체에 넘깁니다.
remote.setCommand(command);
Remote객체에서 buttonClicked메소드를 실행합니다.
remote.buttonClick();
12. Command객체를 Remote객체에 넘깁니다.(선택)
// In main method
// 객체 생성
Remote remote = new Remote();
Aircon aircon = new Aircon();
AirconCommand ac = new AirconCommand(aircon);
!
// Command 객체 넘기기
remote.setCommand(ac);
14. 다른 가전제품을 조작하려면?
// 객체 생성
tvCommand tc = new AirconCommand(tv);
!
// Command 객체 넘기기
remote.setCommand(tc);
!
// 버튼 누르기
remote.buttonClick();
15. 참고 : Remote Class
public class remoteTest {
Command slot;
public void setCommand(Command command) {
slot = command;
}
public void buttonClick() {
slot.execute();
}
}
16. 이제 새로운 제품이 추가되면,
Command Interface를 구현하기만 하면 됩니다.
참 쉽죠?