객체들을 새로운 행동을 포함한 특수 래퍼 객체에 넣어서 위 행동들을 해당 객체에 연결시키는 구조적 디자인 패턴
package ch06;
import ch06.notification.BasicNotifier;
import ch06.notification.EmailNotifier;
import ch06.notification.Notifier;
import ch06.notification.SmsNotifier;
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);
}
}
package ch06.notification;
public interface Notifier {
void send();
}
package ch06.notification;
public class EmailNotifier implements Notifier {
// 기본 알림 의존 생성
Notifier notifier;
// 디폴트 생성자
public EmailNotifier() {}
public EmailNotifier(Notifier notifier) {
this.notifier = notifier;
}
public void send() {
// 데코레이터 패턴은 null 처리 필수
if(notifier != null) {
notifier.send();
}
System.out.println("이메일 알림");
}
}
package ch06.notification;
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("문자 알림");
}
}
package ch06.notification;
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("기본 알림");
}
}
Share article