1. 정의
- 기능을 처리하는 클래스와 구현을 담당하는 추상 클래스로 구분한다. 구현 및 추상 클래스 모두 독립적인 변경이 필요할 때 사용된다.
💡 기존 시스템을 변경하지 않고 기능을 확장할 수 있다.
2. 예시
- 어떤 리모컨을 쓸지, 어떤 티비를 쓸지 잘 모른다. 사용하는 리몬컨과 티비가 자주 바뀌기 때문에 쉽게 변경해서 사용할 수 있는 구조가 필요하다.
3. 그림
4. 클래스 다이어그램
5. 코드
public class Client {
public static void main(String[] args){
System.out.println("[로지택 리모컨]");
RemoteControl control = new LogitechRemoteControl(new SamsungTv());
control.nextChannel();
control.nextChannel();
control = new LogitechRemoteControl(new LGTv());
control.nextChannel();
System.out.println("[한성 리모컨]");
control = new HansungRemoteControl(new SamsungTv());
control.nextChannel();
control = new HansungRemoteControl(new LGTv());
control.nextChannel();
control.nextChannel();
}
}
public interface Tv {
String tuneChannel(int channel);
}
public class SamsungTv implements Tv{
@Override
public String tuneChannel(int channel) {
return "삼성 TV 채널 상승 : " + channel;
}
}
public class LGTv implements Tv{
@Override
public String tuneChannel(int channel) {
return "LG TV 채널 상승 : " + channel;
}
}
public abstract class RemoteControl {
protected Tv tv;
protected RemoteControl(Tv tv){
this.tv = tv;
}
protected abstract void nextChannel();
public void setChannel(int channel){
System.out.println(tv.tuneChannel(channel));
}
}
public class LogitechRemoteControl extends RemoteControl{
private int currentChannel = 1;
public LogitechRemoteControl(Tv tv) {
super(tv);
}
public void nextChannel(){
setChannel(currentChannel++);
}
}
public class HansungRemoteControl extends RemoteControl{
private int currentChannel = 1;
public HansungRemoteControl(Tv tv) {
super(tv);
}
public void nextChannel(){
setChannel(currentChannel++);
}
}
https://github.com/kang-seongbeom/design_pattern
💡 Github에서 디자인 패턴 코드를 볼 수 있습니다.
6. 설명
- 구현 부분인 Tv와 추상화 부분인 RemoteControl을 완전히 결합하지 않았기 때문에, 구현과 추상화를 구분할 수 있다.
- 구현과 추상화 부분은 가각 독립적으로 확장할 수 있다.
- 단, 디자인이 복잡해진다.
'디자인 패턴' 카테고리의 다른 글
디자인 패턴 - 플라이웨이트 패턴(Flyweight Pattern) (0) | 2022.11.18 |
---|---|
디자인 패턴 - 빌더 패턴(Builder Pattern) (0) | 2022.11.18 |
디자인 패턴 - (원격)프록시 패턴 (Proxy Pattern) (0) | 2022.11.18 |
디자인 패턴 - 상태 패턴(State Pattern) (0) | 2022.11.18 |
디자인 패턴 - 컴포지트 패턴(Composite Pattern) (0) | 2022.11.18 |