반응형
행동 패턴 - Template Method
해결하려는 문제
- 문제 해결의 큰 흐름은 유지하고, 단계별 처리는 위임하고자 할 때
- 구체적인 처리 방법은 하위 클래스로 위임하고자 할 때
public class Main {
public static void main(String[] args) {
// Keyboard keyboard = new LoggingKeyboard();
Keyboard keyboard = new EscKeyMonitoringKeyboard();
keyboard.press(new AlphabetKey("A"));
keyboard.press(new AlphabetKey("B"));
keyboard.press(new AlphabetKey("C"));
keyboard.press(new AlphabetKey("ESC"));
}
}
public abstract class Keyboard {
public void press(KeyboardKey keyboardKey) {
keyDown(keyboardKey);
System.out.println("입력된 키 : " + keyboardKey.getKey());
keyUp(keyboardKey);
}
protected abstract void keyUp(KeyboardKey key);
protected abstract void keyDown(KeyboardKey key);
}
public class LoggingKeyboard extends Keyboard {
@Override
protected void keyUp(KeyboardKey key) {
System.out.println("logging...key up : " + key.getKey());
}
@Override
protected void keyDown(KeyboardKey key) {
System.out.println("logging...key down : " + key.getKey());
}
}
public interface KeyboardKey {
String getKey();
}
public class Alphabet implements KeyboardKey {
private String keyName;
public AlphabetKey(String keyName) {
this.keyName = keyName;
}
@Override
public String getKey() {
return keyName;
}
}
public class EscKeyMonitoringKeyboard extends Keyboard {
@Override
protected void keyUp(Keyboard key) {
if (isEscKey(key)) {
System.out.println("ESC logging...key up : " + key.getKey());
}
}
@Override
protected void keyDown(Keyboard key) {
if (isEscKey(key)) {
System.out.println("ESC logging...key down : " + key.getKey());
}
}
private boolean isEscKey(KeyboardKey key) {
// return key.getKey().equalsIgnoreCase("ESC");
return "ESC".equalsIgnoreCase(key.getKey());
}
}
반응형
'cs > java-spring-boot' 카테고리의 다른 글
[Zero-base] 11-12. 디자인 패턴 정리 (0) | 2022.03.15 |
---|---|
[Zero-base] 11-11. 책임연쇄(Chain of responsibility) (0) | 2022.03.15 |
[Zero-base] 11-9. 스트러티지(Strategy) (0) | 2022.03.15 |
[Zero-base] 11-8. 프록시(Proxy) (0) | 2022.03.15 |
[Zero-base] 11-7. 데코레이터(Decorator) (0) | 2022.03.15 |