목차
1.4.2 소프트웨어 설계
1.4.2.7 디자인 패턴의 개념과 대표 패턴
디자인 패턴의 개념과 분류
- 정의: 디자인 패턴(Design Pattern) 은 SW 설계의 특정 맥락에서 반복되는 문제에 대한, 일반적이고 재사용 가능한 해결 방법입니다. 모범 사례를 공식화한 것으로, 주로 클래스, 객체 사이의 상호작용과 관계로 나타냅니다. 대표는 GoF(Gamma, Helm, Johnson, Vlissides, 1994)의 23개 패턴입니다.
- 패턴의 4요소(GoF): 이름, 문제(적용 상황), 해법(구조, 참여자, 협력), 결과(장단점)
- 장점: 검증된 설계를 재사용하고, 개발자 사이에 공통 어휘가 생기며, 변경에 유연해집니다.
- 분류
- 목적(Purpose) 기준
- 생성(Creational) 5개: 객체 생성 과정에 관여
- 구조(Structural) 7개: 클래스, 객체를 합성, 조합해 더 큰 구조를 만듭니다
- 행위(Behavioral) 11개: 객체 사이의 상호작용과 책임 분산
- 범위(Scope) 기준
- 클래스 패턴: 상속으로 관계를 맺고 컴파일 시 정적으로 정해집니다. Factory Method, Adapter(클래스), Interpreter, Template Method 4개뿐입니다.
- 객체 패턴: 객체 합성으로 관계를 맺고 런타임에 바꿀 수 있습니다. 나머지 전부
- 목적(Purpose) 기준
- 암기(개수): 생성 5, 구조 7, 행위 11 = 23
- 생성: 추, 빌, 팩, 프, 싱(Abstract Factory, Builder, Factory Method, Prototype, Singleton)
- 구조: 어, 브, 컴, 데, 퍼, 플, 프(Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy)
- 행위: 나머지 11개(Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor)
GoF 23 패턴: 의도와 식별 단서
| 목적 | 패턴 | 코드, 상황 식별 단서 |
|---|---|---|
| 생성 | Abstract Factory | createButton(), createCheckbox()처럼 관련 객체 여러 개를 만드는 메서드 묶음을 가진 팩토리 인터페이스, WinFactory/MacFactory |
| 생성 | Builder | new X.Builder().a().b().build() 메서드 체이닝, 복잡한 객체를 단계별 조립 |
| 생성 | Factory Method | 상위 클래스가 abstract Product createXxx()를 선언하고 하위 클래스가 무엇을 new할지 결정 |
| 생성 | Prototype | clone(), Cloneable, 원형 객체 등록 후 복사 |
| 생성 | Singleton | private 생성자 + static 자기 타입 필드 + static getInstance() |
| 구조 | Adapter | 기대 인터페이스(Target)를 구현하면서 다른 인터페이스 객체(Adaptee)를 감싸 메서드 이름, 형식을 바꿔 호출 |
| 구조 | Bridge | 추상 계층이 구현 계층 인터페이스를 필드로 가짐(Shape가 Color 참조), 두 계층을 따로 확장 |
| 구조 | Composite | 잎(File)과 복합체(Directory)가 같은 인터페이스, 복합체가 자식 리스트를 돌며 재귀 호출 |
| 구조 | Decorator | 같은 인터페이스를 구현하면서 같은 타입 객체를 감싸 기능을 덧붙임, new A(new B(new C())) 중첩 |
| 구조 | Facade | 클래스 하나가 여러 서브시스템 객체를 조합해 호출하는 고수준 메서드 제공, 클라이언트는 그것만 호출 |
| 구조 | Flyweight | 팩토리가 Map 캐시로 같은 키면 기존 객체 재사용, 공유 상태와 비공유 상태 분리 |
| 구조 | Proxy | 실제 객체와 같은 인터페이스, 내부에서 접근 제어, 지연 생성(null이면 new), 캐싱, 원격 호출 후 위임 |
| 행위 | Chain of Responsibility | next 처리자 필드, "처리 못 하면 next.handle()"(결재 라인, 필터 체인) |
| 행위 | Command | execute(), undo() 인터페이스, 호출자(Invoker)가 명령 객체를 저장, 실행 |
| 행위 | Interpreter | 문법 규칙마다 클래스, interpret(context) 재귀 |
| 행위 | Iterator | hasNext(), next() |
| 행위 | Mediator | 객체끼리 서로 참조하지 않고 중재자에게만 메시지(채팅방, 관제탑) |
| 행위 | Memento | save()가 상태 스냅샷 객체를 반환, restore(m), 보관자(Caretaker)가 스택에 보관 |
| 행위 | Observer | 주체(Subject)가 옵저버 목록을 갖고 attach/detach/notify → 각 옵저버의 update() 호출 |
| 행위 | State | 상태마다 클래스, 문맥(Context)이 현재 상태 객체에 위임하고 상태 객체가 다음 상태로 교체 |
| 행위 | Strategy | 알고리즘 인터페이스와 구현들, 문맥이 setStrategy()로 밖에서 교체(할인, 정렬, 결제 방식) |
| 행위 | Template Method | 상위 추상 클래스의 final 템플릿 메서드가 abstract 단계 메서드를 순서대로 호출, 하위가 단계를 구현 |
| 행위 | Visitor | 요소에 accept(Visitor v), 방문자에 visit(ElementA), visit(ElementB) |
- ⚠️ 함정
- Interpreter는 클래스-행위 패턴이고, Iterator는 객체-행위 패턴입니다.
- Singleton은 '최대 N개'로 제한하는 용도로도 설명합니다.
코드로 보는 생성 패턴
아래 코드는 모두 한 파일로 모았습니다(출력: true / pdf hwp / MacButton MacCheckbox / Pizza(12,true,false) / true dolly).
// Singleton — ① static 자기 타입 필드 ② private 생성자 ③ static 접근 메서드
class Config {
private static final Config INSTANCE = new Config();
private Config() { }
public static Config getInstance() { return INSTANCE; }
} // Config.getInstance() == Config.getInstance() → true
// Factory Method — 생성 절차는 상위가, 무엇을 new할지는 하위 클래스가
abstract class App {
public String newDocument() { Doc d = createDoc(); return d.open(); }
protected abstract Doc createDoc(); // 팩토리 메서드
}
class PdfApp extends App { protected Doc createDoc() { return new PdfDoc(); } }
class HwpApp extends App { protected Doc createDoc() { return new HwpDoc(); } }
// Abstract Factory — 관련 제품군(Button + Checkbox)을 한 팩토리가 만든다
interface GuiFactory { Button createButton(); Checkbox createCheckbox(); }
class MacFactory implements GuiFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
// Builder — 단계별로 조립한 뒤 build()
Pizza p = new Pizza.Builder().size(12).cheese().build();
// Prototype — 기존 객체를 복제해 생성
Sheep b = a.clone(); // a != b, 내용은 같다
- Singleton 늦은 초기화(처음 쓸 때 생성)는
if (inst == null) inst = new X();로 쓰고, 멀티스레드에서는synchronized나 홀더 클래스로 보호합니다. - Singleton 예제는
Start.→인스턴스가 생성되었습니다.→obj1과 obj2는 같은 인스턴스입니다.→End.순서로 출력합니다. static 필드는 클래스를 처음 사용할 때 초기화되므로 생성 메시지가Start.뒤에 나옵니다. 생성자는 한 번만 실행됩니다.
코드로 보는 구조 패턴
한 파일로 모은 코드입니다(출력: Adapter ab, Composite 22, Decorator 3800, Proxy 로딩 횟수 0 → 1, Flyweight "banana"의 풀 크기 3).
// Adapter — Target(Iterator)을 구현하고 Adaptee(Enumeration)를 감싸 호출을 변환(파일럿 11번 구조)
class EnumerationIterator implements Iterator<Object> {
private final Enumeration<?> e; // Adaptee 참조 → 객체 어댑터
EnumerationIterator(Enumeration<?> e) { this.e = e; }
public boolean hasNext() { return e.hasMoreElements(); }
public Object next() { return e.nextElement(); }
public void remove() { throw new UnsupportedOperationException(); }
}
// Bridge — 추상 계층(Shape)이 구현 계층(Color)을 필드로 참조: new Circle(new Red())
abstract class Shape {
protected final Color color;
Shape(Color c) { color = c; }
abstract String draw();
}
class Circle extends Shape {
Circle(Color c) { super(c); }
String draw() { return "circle-" + color.fill(); }
}
// Composite — 잎과 복합체가 같은 인터페이스, 복합체는 자식에게 재귀 위임
interface Node { int size(); }
class FileNode implements Node {
private final int bytes;
FileNode(int b) { bytes = b; }
public int size() { return bytes; }
}
class DirNode implements Node {
private final List<Node> children = new ArrayList<>();
DirNode add(Node n) { children.add(n); return this; }
public int size() { int sum = 0; for (Node n : children) sum += n.size(); return sum; }
}
// Decorator — 같은 인터페이스를 구현하며 같은 타입을 감싸 기능 추가
abstract class CoffeeDecorator implements Coffee {
protected final Coffee inner;
CoffeeDecorator(Coffee c) { inner = c; }
}
class Milk extends CoffeeDecorator {
Milk(Coffee c) { super(c); }
public int cost() { return inner.cost() + 500; }
} // new Syrup(new Milk(new Espresso())).cost() → 3000 + 500 + 300 = 3800
// Facade — 복잡한 서브시스템 앞의 단일 창구
class ComputerFacade {
private final Cpu cpu = new Cpu();
private final Memory mem = new Memory();
private final Disk disk = new Disk();
String start() { return disk.read() + ">" + mem.load() + ">" + cpu.boot(); }
}
// Proxy — 같은 인터페이스, 실제 객체 생성을 필요할 때까지 미룸(가상 프록시)
class ImageProxy implements Image {
private final String file;
private RealImage real;
ImageProxy(String f) { file = f; }
public String show() {
if (real == null) real = new RealImage(file); // 지연 로딩
return real.show();
}
}
// Flyweight — 같은 키면 기존 객체를 공유
class GlyphFactory {
private static final Map<Character, Glyph> pool = new HashMap<>();
static Glyph get(char c) { return pool.computeIfAbsent(c, Glyph::new); }
}
코드로 보는 행위 패턴
한 파일로 모은 코드입니다(출력: Observer [phone25, tv25], Strategy 10000 → 9000, Template boil>tea>pour, Command 실행 후 true → undo 후 false, State G→Y→R→G, Memento ab, Chain 50→TeamLead, 500→Manager, 5000→Director, 50000→none).
// Observer — 주체가 목록을 들고 있다가 상태가 바뀌면 모두에게 update()
interface Observer { void update(int temp); }
class WeatherStation {
private final List<Observer> observers = new ArrayList<>();
void attach(Observer o) { observers.add(o); }
void setTemp(int t) { for (Observer o : observers) o.update(t); }
}
// Strategy — 알고리즘을 인터페이스로 두고 실행 중 교체(합성)
interface DiscountPolicy { int apply(int price); }
class Order {
private DiscountPolicy policy = new NoDiscount();
void setPolicy(DiscountPolicy p) { policy = p; }
int pay(int price) { return policy.apply(price); }
}
// Template Method — 골격은 상위의 final 메서드, 달라지는 단계만 하위가(상속)
abstract class Beverage {
public final String make() { return boil() + ">" + brew() + ">" + pour(); }
private String boil() { return "boil"; }
private String pour() { return "pour"; }
protected abstract String brew();
}
class Tea extends Beverage { protected String brew() { return "tea"; } }
// Command — 요청을 객체로. 호출자는 내용을 모른 채 실행·취소
interface Command { void execute(); void undo(); }
class RemoteControl {
private final Deque<Command> history = new ArrayDeque<>();
void press(Command c) { c.execute(); history.push(c); }
void undo() { if (!history.isEmpty()) history.pop().undo(); }
}
// State — 상태마다 클래스, 상태 객체가 다음 상태를 정한다(if/switch 제거)
interface State { State next(); String name(); }
class Green implements State {
public State next() { return new Yellow(); }
public String name() { return "G"; }
}
class TrafficLight {
private State state = new Green();
void change() { state = state.next(); }
}
// Memento — 상태 스냅샷을 저장했다가 복원
class Editor {
private String text = "";
void type(String s) { text += s; }
Snapshot save() { return new Snapshot(text); }
void restore(Snapshot m) { text = m.state(); }
}
record Snapshot(String state) { }
// Chain of Responsibility — 처리하지 못하면 다음 처리자에게 넘긴다
abstract class Approver {
private Approver next;
Approver setNext(Approver n) { next = n; return n; }
String approve(int amount) {
if (canHandle(amount)) return getClass().getSimpleName();
return next == null ? "none" : next.approve(amount);
}
abstract boolean canHandle(int amount);
}
헷갈리는 패턴 쌍
| 쌍 | 구분 포인트 |
|---|---|
| Adapter vs Facade | Adapter는 기존 인터페이스를 다른 모양으로 변환합니다. Facade는 여러 서브시스템 위에 단순한 새 창구를 만듭니다 |
| Adapter vs Decorator vs Proxy | 셋 다 감싸는 구조(wrapper)입니다. Adapter는 인터페이스가 바뀐다. Decorator는 같은 인터페이스에 기능을 더한다(중첩 가능). Proxy는 같은 인터페이스로 접근을 제어한다(지연 생성, 권한, 캐시) |
| Adapter vs Bridge | Adapter는 이미 있는 불일치를 나중에 맞춥니다. Bridge는 추상과 구현을 설계 초기부터 분리합니다 |
| Composite vs Decorator | 둘 다 재귀 구조입니다. Composite는 자식이 여럿인 부분-전체 트리, Decorator는 감싼 객체 하나에 기능을 더합니다 |
| Strategy vs State | 구조는 같습니다(문맥이 인터페이스에 위임). Strategy는 클라이언트가 알고리즘을 골라 주입하고, State는 상태 객체가 스스로 다음 상태로 전이합니다 |
| Strategy vs Template Method | Strategy는 합성으로 알고리즘 전체를 런타임에 교체합니다. Template Method는 상속으로 골격을 고정하고 일부 단계만 재정의합니다 |
| Factory Method vs Abstract Factory | Factory Method는 상속으로 제품 하나의 생성을 하위 클래스에 맡깁니다. Abstract Factory는 관련 제품군을 만드는 인터페이스를 합성으로 제공합니다 |
| Observer vs Mediator | Observer는 1:N 통지입니다. Mediator는 N:M 상호작용을 중재자 하나로 모은다 |
| Command vs Strategy | Command는 무엇을 할지(요청) 를 객체로 만듭니다(Undo, 큐). Strategy는 어떻게 할지(방법) 를 바꿉니다 |
| Memento vs Command의 undo | Memento는 상태 스냅샷으로 복원합니다. Command의 undo는 역연산으로 되돌립니다 |
| Singleton vs Flyweight | Singleton은 클래스당 인스턴스 1개, Flyweight는 키(공유 상태)마다 1개를 공유합니다 |
Java 표준 라이브러리 속 패턴(식별 연습)
| 코드 | 패턴 |
|---|---|
Runtime.getRuntime() | Singleton |
StringBuilder.append().append(), HttpRequest.newBuilder()…build() | Builder |
Object.clone() | Prototype |
Arrays.asList(배열), new InputStreamReader(System.in)(바이트 → 문자 스트림) | Adapter |
new BufferedReader(new FileReader(f)), Collections.synchronizedList(list) | Decorator |
java.lang.reflect.Proxy, JPA 지연 로딩 객체 | Proxy |
AWT Container(Component를 담는 Component) | Composite |
Integer.valueOf() 캐시(-128~127), 문자열 상수 풀 | Flyweight |
Iterator의 hasNext()/next() | Iterator |
이벤트 리스너, PropertyChangeListener | Observer |
Collections.sort(list, comparator) | Strategy |
HttpServlet.service()가 doGet()/doPost() 호출, AbstractList | Template Method |
Runnable을 스레드 풀에 제출 | Command |
서블릿 FilterChain, 예외 처리 위임 | Chain of Responsibility |
java.util.regex.Pattern | Interpreter |
Files.walkFileTree(path, FileVisitor) | Visitor |
java.util.Observable/Observer는 Java 9부터 deprecated입니다. 패턴 개념은 그대로 유효합니다.- 📌 기출 연결
- 파일럿 11번 "서비스가 제공하는 인터페이스를 클라이언트가 기대하는 인터페이스로 변환", "호환되지 않는 인터페이스를 함께 작동"이라는 설명과 클래스도(Client → «Interface» Iterator ◁- - EnumerationIterator → «Interface» Enumeration)를 줬습니다.
- 정답은 Adapter입니다(오답: Decorator, Bridge, Command).
- 역할: Target = Iterator, Adaptee = Enumeration, Adapter = EnumerationIterator
- Adaptee를 상속하지 않고 참조(위임) 하므로 객체 어댑터입니다.
- 25회 후기 소스 코드를 보고 구조 패턴을 고르는 객관식이 나왔습니다. 위 구조 패턴 7개의 코드 단서를 구별해 둡니다.
- 웹 후기 22회 코드를 보고 디자인 패턴 이름을 맞히고 설명하는 복합 문제, [12회] 디자인 패턴 2~3문제, [11회] 클래스 다이어그램을 보고 패턴을 묻는 문제가 나왔습니다.
- 파일럿 11번 "서비스가 제공하는 인터페이스를 클라이언트가 기대하는 인터페이스로 변환", "호환되지 않는 인터페이스를 함께 작동"이라는 설명과 클래스도(Client → «Interface» Iterator ◁- - EnumerationIterator → «Interface» Enumeration)를 줬습니다.
- 출처: (Gamma 외 "Design Patterns", 1994)