데코레이터 패턴은 기존 객체에 추가 기능을 동적으로 부여하는 기법이다.
1. 정의
데코레이터 패턴(Decorator Pattern)은 구조 패턴(Structural Pattern) 중 하나로, 객체에 새로운 기능을 동적으로 추가할 수 있게 해주는 디자인 패턴이다. 이 패턴은 기존 객체를 변경하지 않고, 객체를 감싸는 방식으로 기능을 확장하는 데 사용된다.
2. 예제 코드
public interface Notifier {
void send();
}
public class BasicNotifier implements Notifier {
Notifier notifier;
public BasicNotifier() {}
public BasicNotifier(Notifier notifier) {
this.notifier = notifier;
}
public void send() {
if(notifier !=null) {
notifier.send();
}
System.out.println("기본 알림");
}
}
public class EmailNotifier implements Notifier {
Notifier notifier;
public EmailNotifier() {}
public EmailNotifier(Notifier notifier) {
this.notifier = notifier;
}
public void send(){
if(notifier !=null) {
notifier.send();
}
System.out.println("이메일 알림");
}
}
public class SmsNotifier implements Notifier {
Notifier notifier;
public SmsNotifier() {}
public SmsNotifier(Notifier notifier) {
this.notifier = notifier;
}
public void send(){
if(notifier !=null) {
notifier.send();
}
System.out.println("SMS 알림");
}
}
public class App {
public static void 알림(Notifier notifier) {
notifier.send();
}
// 데코레이터 패턴 : 기능 확장 (핵심)
public static void main(String[] args) {
// 1. 전체 알림(기본알림 -> 문자알림 -> 이메일알림)
Notifier n1 = new EmailNotifier(new SmsNotifier(new BasicNotifier()));
알림(n1);
// 2. 전체 알림(기본알림 -> 이메일알림 -> 문자알림)
Notifier n2 = new SmsNotifier(new EmailNotifier(new BasicNotifier()));
알림(n2);
// 3. 기본 알림
Notifier n3 = new BasicNotifier();
알림(n3);
// 4. 기본 알림 + 문자 알림
Notifier n4 = new SmsNotifier(new BasicNotifier());
알림(n4);
// 5. 기본 알림 + 이메일 알림
Notifier n5 = new EmailNotifier(new BasicNotifier());
알림(n5);
// 6. 이메일 알림
Notifier n6 = new EmailNotifier();
알림(n6);
// 7. 문자 알림
Notifier n7 = new SmsNotifier();
알림(n7);
// 8. 문자 + 이메일
Notifier n8 = new EmailNotifier(new SmsNotifier());
알림(n8);
}
}
3. 정리
Notifier
인터페이스- 알림을 보내는
send()
메서드를 정의한 인터페이스이다.
BasicNotifier, EmailNotifier, SmsNotifier
클래스Notifier
객체를 필드 값으로 가지고 있는 데코레이터이다.send()
메서드를 구현해 각각의 알림을 보낸다.
App
클래스- 다양한 데코레이터를 조합하여 알림 기능을 동적으로 확장한 예시를 보여준다.
Share article