디자인 패턴(Design Pattern)은 소프트웨어 개발 과정에서 자주 마주치는 설계 문제들에 대한 '검증된 모범 답안'입니다. 건축에서 건물을 지을 때 설계 도면의 패턴이 있듯, 소프트웨어에서도 재사용 가능하고 유지보수가 쉬운 구조를 만들기 위한 공통된 패턴이 존재합니다.
1995년, 이른바 GoF(Gang of Four)라 불리는 4명의 전문가가 23가지의 핵심 패턴을 '생성', '구조', '행위' 3가지 카테고리로 정리하여 발표했습니다. 본 과정에서는 이 23가지 패턴 전부를 실무와 직결되는 Java 예제와 함께 마스터합니다.
※ 본 과정에서는 위 23개의 GoF 디자인 패턴 전체를 상세히 다루며, 각 패턴별 Java 소스코드 예제를 함께 제공합니다.
수많은 시행착오 끝에 만들어진 정답지이므로, 코드의 결합도를 낮추고 응집도를 높이는 객체지향의 원칙(SOLID)을 자연스럽게 지킬 수 있습니다.
모든 문제에 패턴을 적용하려는 '과유불급'을 조심해야 합니다. 단순한 로직에 복잡한 패턴을 억지로 끼워 넣으면 오히려 코드가 읽기 힘들어집니다.
싱글톤 패턴(Singleton Pattern)은 애플리케이션 전체에서 클래스의 인스턴스(객체)가 오직 단 하나만 생성되도록 강제하고, 어디서든 그 인스턴스에 접근할 수 있도록 전역적인 접근점(Global Access Point)을 제공하는 생성(Creational) 디자인 패턴입니다.
외부에서 new 키워드를 사용해 객체를 마구잡이로 찍어내는 것을 막기 위해 생성자를 Private으로 숨기는 것이 핵심입니다.
| 장점 (Pros) | 단점 및 한계 (Cons) |
|---|---|
|
1. 메모리 낭비 방지: 수많은 요청이 들어와도 객체를 매번 생성하지 않으므로 메모리를 크게 절약합니다. 2. 상태 공유 용이: 전역 인스턴스이므로 다른 클래스의 인스턴스들이 이 싱글톤 객체의 데이터를 쉽게 공유할 수 있습니다. |
1. 멀티스레드 동시성 문제: 여러 스레드가 동시에 인스턴스를 생성하려 할 때 락(Lock) 처리를 제대로 안 하면 인스턴스가 2개 생길 수 있습니다. 2. 단위 테스트(Unit Test)의 어려움: 상태를 공유하는 전역(Global) 성격을 띠기 때문에 각 테스트가 독립적으로 실행되기 매우 까다롭습니다. |
애플리케이션 내에서 공용으로 사용해야 하고, 여러 개가 만들어지면 로직이 꼬이거나 리소스가 낭비되는 객체들에 사용합니다. 대표적으로 데이터베이스 커넥션 풀(DB Connection Pool), 로거(Logger), 애플리케이션 환경 설정(Configuration Manager), 스레드 풀(Thread Pool) 관리자 등이 있습니다.
// 📂 DatabaseConnection.js (JavaScript)
// 모듈 스코프나 클로저를 활용한 싱글톤 패턴
class DatabaseConnection {
constructor() {
if (DatabaseConnection.instance) {
return DatabaseConnection.instance;
}
console.log("데이터베이스 연결 초기화 완료");
DatabaseConnection.instance = this;
return this;
}
executeQuery(query) {
console.log(`쿼리 실행: ${query}`);
}
}
// 📂 main.js (사용 예시)
const db1 = new DatabaseConnection();
const db2 = new DatabaseConnection();
console.log("인스턴스가 동일한가?:", db1 === db2); // true
db1.executeQuery("SELECT * FROM users");팩토리 메서드 패턴(Factory Method Pattern)은 부모 클래스에서 객체(Product)를 생성하기 위한 인터페이스를 정의하지만, 실제로 어떤 클래스의 인스턴스를 생성할지에 대한 결정은 자식 클래스(Subclass)가 내리도록 미루는 생성 디자인 패턴입니다. 즉, 직접 new 키워드를 쓰지 않고 객체 생성을 '공장'에 위임하는 방식입니다.
이 패턴은 크게 물건을 만들어내는 공장(Creator)과 만들어진 제품(Product) 두 축으로 나뉘며, 각각 추상화(Interface/Abstract)와 구체화(Concrete) 단계로 구현됩니다.
| 장점 (Pros) | 단점 및 한계 (Cons) |
|---|---|
|
1. 완벽한 OCP 원칙 준수: 새로운 제품(예: 총, 지팡이)이 추가되어도 기존 클래스를 전혀 수정할 필요 없이, 새로운 제품 클래스와 공장 서브클래스만 추가하면 됩니다. 2. 객체 생성 로직 캡슐화: 비즈니스 로직( testWeapon)에서 직접 new Sword()를 호출하지 않아 결합도(Coupling)가 낮아집니다.
|
1. 클래스 폭발 (Class Explosion): 무기가 1개 추가될 때마다 Weapon 서브클래스 1개, Blacksmith 서브클래스 1개, 총 2개의 클래스가 계속 늘어나 파일 관리가 복잡해질 수 있습니다.2. 코드가 장황해짐: 간단한 프로그램에서는 오히려 단순 new 키워드나 '정적 팩토리 메서드(Static Factory)'를 쓰는 것이 직관적입니다.
|
자바 스프링(Spring) 프레임워크의 핵심인 IoC 컨테이너(BeanFactory, ApplicationContext)가 바로 이 팩토리 패턴 철학의 끝판왕입니다. 개발자는 '이런 객체가 필요해'라고 설정만 해두면, 컨테이너(초대형 팩토리)가 알아서 객체를 생성하고 조립하여 주입(DI)해줍니다. 실무에서는 보통 패턴의 정석적인 클래스 분리보다는 Enum이나 정적 팩토리 헬퍼 클래스를 활용하여 더 실용적으로 압축해 쓰는 경우가 많습니다.
// 📂 factory.js (JavaScript)
// JS는 인터페이스가 없으므로 클래스와 Error 런타임 검증을 활용합니다.
// Product 역할
class Sword {
attack() { console.log("검으로 베기! 슉슉!"); }
}
class Bow {
attack() { console.log("활쏘기! 피융~"); }
}
// Creator 역할 (추상 클래스 흉내)
class Blacksmith {
// 팩토리 메서드: 서브클래스가 반드시 구현해야 함
craftWeapon() {
throw new Error("서브클래스에서 craftWeapon()을 구현해야 합니다.");
}
// 핵심 비즈니스 로직은 Creator에 위치
testWeapon() {
const weapon = this.craftWeapon();
weapon.attack();
}
}
// Concrete Creator A
class SwordBlacksmith extends Blacksmith {
craftWeapon() { return new Sword(); }
}
// Concrete Creator B
class BowBlacksmith extends Blacksmith {
craftWeapon() { return new Bow(); }
}
// 📂 main.js (사용 예시)
const smith1 = new SwordBlacksmith();
smith1.testWeapon(); // 출력: 검으로 베기! 슉슉!
const smith2 = new BowBlacksmith();
smith2.testWeapon(); // 출력: 활쏘기! 피융~빌더 패턴(Builder Pattern)은 복잡한 객체의 생성 과정과 표현 방법을 분리하여, 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 생성 디자인 패턴입니다. 매개변수가 많은 객체를 만들 때 생성자(Constructor) 오버로딩이 끝도 없이 늘어나는 '점층적 생성자 패턴(Telescoping Constructor Pattern)'의 문제를 해결하기 위해 고안되었습니다.
자바(Java) 진영에서 가장 널리 쓰이는 Effective Java 스타일의 정적 내부 클래스(Static Inner Class) 빌더 패턴 구조입니다. 체이닝(Chaining) 기법을 통해 객체를 직관적이고 안전하게 조립할 수 있습니다.
| 장점 (Pros) | 단점 및 한계 (Cons) |
|---|---|
|
1. 가독성(Readability) 극대화: 매개변수 위치에 얽매이지 않고 메서드 이름으로 명확하게 어떤 값을 세팅하는지 알 수 있습니다. (메서드 체이닝 기법) 2. 불변 객체(Immutable Object) 생성: Setter 메서드를 열어두지 않고도 완벽하게 필드가 세팅된 불변 객체를 생성할 수 있어 스레드 안정성이 높아집니다. |
1. 코드량 증가: 객체를 생성하기 위해 별도의 Builder 클래스를 만들어야 하므로, 필드가 몇 개 없는 단순한 객체라면 오버엔지니어링(Over-engineering)이 될 수 있습니다. 2. 모던 언어의 지원: Kotlin, Python, TypeScript 등 Named Arguments(이름 있는 매개변수)를 자체 지원하는 모던 언어에서는 빌더 패턴의 필요성이 크게 떨어집니다. |
// 📂 Hamburger.js (JavaScript)
// 자바스크립트는 객체 리터럴이 훌륭하여 빌더의 필요성이 낮지만, 구조적 제한을 위해 명시적으로 구현할 수 있습니다.
class Hamburger {
// 3. 빌더에서 조립된 최종 데이터를 받아 불변 객체(혹은 캡슐화된 상태)로 만듦
constructor(builder) {
this.patty = builder.patty;
this.bun = builder.bun || '참깨 번';
this.hasCheese = builder.hasCheese || false;
}
showMenu() {
console.log(`🍔 주문: ${this.bun}, ${this.patty} 패티, 치즈 추가: ${this.hasCheese ? 'O' : 'X'}`);
}
}
class HamburgerBuilder {
constructor(patty) {
this.patty = patty; // 필수 항목
}
// 1. 선택 항목은 체이닝(Chaining)을 위해 return this를 반환
withBun(bun) {
this.bun = bun;
return this;
}
addCheese() {
this.hasCheese = true;
return this;
}
// 2. 최종 객체 반환
build() {
return new Hamburger(this);
}
}
// 📂 main.js (사용 예시)
const burger1 = new HamburgerBuilder("순쇠고기")
.withBun("브리오슈 번")
.addCheese()
.build();
burger1.showMenu(); // 🍔 주문: 브리오슈 번, 순쇠고기 패티, 치즈 추가: O
// 매개변수 순서 헷갈릴 일이 없고, 치즈를 뺀 버전도 쉽게 생성 가능
const burger2 = new HamburgerBuilder("새우").build();
burger2.showMenu(); // 🍔 주문: 참깨 번, 새우 패티, 치즈 추가: X프로토타입 패턴(Prototype Pattern)은 원본 객체를 복제(Clone)하여 새로운 객체를 생성하는 패턴입니다. 객체를 new 키워드로 생성하고 데이터베이스 조회 등을 통해 복잡하게 초기화하는 과정이 매우 비쌀(Cost가 높을) 때, 이미 완벽하게 세팅된 '프로토타입 객체'를 하나 만들어두고 이를 메모리 상에서 통째로 복사해서 사용하면 성능을 극적으로 높일 수 있습니다.
클라이언트는 구체적인 클래스의 이름을 몰라도 clone() 메서드만 호출하면 원본과 완전히 동일한 상태의 새로운 인스턴스를 얻을 수 있습니다.
언어 차원에서 제공하는 기본적인 복제 기능(예: 자바의 clone(), 자바스크립트의 Object.assign())은 얕은 복사(Shallow Copy)를 수행합니다. 즉, 객체 내부에 배열이나 다른 객체의 참조(Reference)가 있다면 메모리 주소만 복사되어 원본과 클론이 내부 객체를 공유하게 됩니다. 이를 방지하려면 내부 참조 객체들까지 재귀적으로 복제하는 깊은 복사(Deep Copy)를 명시적으로 구현해야 합니다.
// 📂 Monster.js (JavaScript)
// 자바스크립트는 언어 자체가 '프로토타입 기반 언어'이므로,
// Object.assign 이나 전개 연산자(...)를 사용해 아주 쉽게 클론을 생성할 수 있습니다.
class Monster {
constructor(type, health, skills) {
this.type = type;
this.health = health;
this.skills = skills; // 배열 (참조 타입)
// ⚠️ 여기서 엄청나게 무거운 DB 조회 작업이 일어난다고 가정합니다.
console.log(`[시스템] ${this.type} 원본 객체 생성 및 리소스 로딩 (매우 무거운 작업)`);
}
// 얕은 복사(Shallow Copy) 메서드
cloneShallow() {
console.log(`[시스템] ${this.type} 얕은 복사 진행 중...`);
return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
}
// 깊은 복사(Deep Copy) 메서드 (참조 타입까지 복사)
cloneDeep() {
console.log(`[시스템] ${this.type} 깊은 복사 진행 중...`);
const cloned = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
// 배열을 새로 할당하여 참조를 분리
cloned.skills = [...this.skills];
return cloned;
}
status() {
console.log(`몬스터: ${this.type} / 체력: ${this.health} / 스킬: [${this.skills.join(', ')}]`);
}
}
// 📂 main.js
// 1. 최초 1회 원본(프로토타입) 생성 시에만 무거운 작업 수행
const ogrePrototype = new Monster("오우거", 100, ["몽둥이 휘두르기", "함성"]);
console.log("-------------------");
// 2. 이후 객체 생성은 얕은 복사를 통해 순식간에 이루어짐
const clonedOgre1 = ogrePrototype.cloneShallow();
const clonedOgre2 = ogrePrototype.cloneDeep();
// 3. 상태 변경 테스트
clonedOgre1.health = 50;
clonedOgre1.skills.push("발구르기"); // 얕은 복사라서 원본과 skills 배열을 공유해버림!
console.log("--- 얕은 복사의 부작용 ---");
ogrePrototype.status(); // 원본 오우거의 스킬에도 '발구르기'가 추가됨
clonedOgre1.status();
console.log("--- 깊은 복사는 안전함 ---");
clonedOgre2.health = 80;
clonedOgre2.skills.push("돌 던지기"); // 깊은 복사라서 배열이 독립적임
clonedOgre2.status();
ogrePrototype.status(); // 원본에는 '돌 던지기'가 없음옵저버 패턴(Observer Pattern)은 한 객체(Subject)의 상태가 변하면 그 객체에 의존하는 모든 객체(Observer)들에게 자동으로 알림이 가고 상태가 갱신되는 1:N(일대다) 의존성을 정의하는 패턴입니다. 유튜버가 새 영상을 올릴 때마다 구독자(Observer)들의 스마트폰으로 알림이 오는 '발행-구독(Pub/Sub)' 메커니즘이 바로 이 패턴의 대표적인 예입니다.
Subject는 어떤 Observer가 자신을 구독하고 있는지 구체적인 타입을 알 필요 없이, 공통된 update() 인터페이스만 호출하면 됩니다. 이를 통해 두 객체는 느슨한 결합(Loose Coupling)을 유지합니다.
새로운 종류의 알림 수신기(이메일, 슬랙, 카카오톡 등)를 추가하더라도 Subject 쪽 코드는 전혀 수정할 필요가 없습니다. 새 수신기가 Observer 인터페이스만 구현하고 attach()를 통해 등록하기만 하면 됩니다. (개방-폐쇄 원칙, OCP 준수)
// 📂 Subject.js (JavaScript)
// 자바스크립트에서는 인터페이스가 없으므로 클래스로 흉내를 냅니다.
class Youtuber {
constructor(name) {
this.name = name;
this.subscribers = []; // Observer들을 담을 배열
this.latestVideo = "";
}
// 구독 (attach)
subscribe(subscriber) {
this.subscribers.push(subscriber);
console.log(`[시스템] ${subscriber.name}님이 ${this.name} 채널을 구독했습니다.`);
}
// 구독 취소 (detach)
unsubscribe(subscriber) {
this.subscribers = this.subscribers.filter(sub => sub !== subscriber);
console.log(`[시스템] ${subscriber.name}님이 구독을 취소했습니다.`);
}
// 새 영상 업로드 시 알림 (notify)
uploadVideo(title) {
this.latestVideo = title;
console.log(`\n▶️ [${this.name}] 새 영상 업로드: "${title}"`);
this.notifyAll();
}
// 모든 구독자에게 상태 업데이트를 전파
notifyAll() {
this.subscribers.forEach(sub => {
sub.update(this.name, this.latestVideo);
});
}
}
// 📂 Observer.js
class Subscriber {
constructor(name) {
this.name = name;
}
// Subject로부터 호출받을 update 메서드
update(youtuberName, videoTitle) {
console.log(`🔔 [${this.name}의 스마트폰] 알림: ${youtuberName}님의 새 영상 "${videoTitle}"이(가) 올라왔습니다!`);
}
}
// 📂 main.js
const techChannel = new Youtuber("IT 꿀팁");
const user1 = new Subscriber("민수");
const user2 = new Subscriber("지영");
const user3 = new Subscriber("철수");
techChannel.subscribe(user1);
techChannel.subscribe(user2);
techChannel.subscribe(user3);
// 영상을 업로드하면 모든 구독자에게 자동으로 알림이 갑니다!
techChannel.uploadVideo("2026년 최신 웹 프레임워크 비교");
techChannel.unsubscribe(user2);
// 구독 취소한 지영이에게는 알림이 가지 않습니다.
techChannel.uploadVideo("개발자가 꼭 알아야 할 디자인 패턴");전략 패턴(Strategy Pattern)은 객체가 할 수 있는 행위(알고리즘)들을 클래스로 캡슐화하고, 동적으로 행위를 자유롭게 교체(Swap)할 수 있게 해주는 패턴입니다. RPG 게임 캐릭터가 무기를 검에서 활로 바꾸면 공격 동작이 완전히 달라지는 것처럼, 수많은 if-else문을 쓰지 않고도 '전략 인터페이스'를 조립(Composition)하는 방식으로 결합도를 낮춥니다.
Context는 구체적인 전략(Concrete Strategy)이 무엇인지 알 필요가 없습니다. 오직 Strategy 인터페이스에만 의존하며, 런타임에 외부에서 전략 객체를 주입(DI)받아 실행합니다.
만약 '마법 지팡이(MagicStrategy)'라는 새로운 무기가 추가되어도, Context(Player) 코드는 단 한 줄도 수정할 필요가 없습니다. 새로운 Strategy 클래스를 만들고 setStrategy()로 주입해주기만 하면 됩니다. 이처럼 알고리즘 캡슐화를 통해 상속보다 훨씬 유연한 구조를 만들 수 있습니다.
// 📂 Strategy.js (JavaScript)
// 자바스크립트는 일급 함수(First-Class Function)를 지원하므로,
// 객체(클래스)를 쓰지 않고 함수만으로도 전략 패턴을 아주 쉽게 구현할 수 있습니다.
// 전략(Strategy) 객체들
const swordStrategy = {
attack: () => console.log("🗡️ 검으로 강하게 벱니다! (데미지: 50)")
};
const bowStrategy = {
attack: () => console.log("🏹 활로 멀리서 쏩니다! (데미지: 30)")
};
const magicStrategy = {
attack: () => console.log("🔥 화염 마법을 시전합니다! (데미지: 100)")
};
// 컨텍스트(Context)
class Player {
constructor(name) {
this.name = name;
this.weaponStrategy = swordStrategy; // 기본 무기
}
setWeapon(strategy) {
this.weaponStrategy = strategy;
console.log(`\n[시스템] ${this.name}의 무기가 변경되었습니다.`);
}
attack() {
console.log(`${this.name}의 공격!`);
this.weaponStrategy.attack(); // 전략 위임
}
}
// 📂 main.js
const hero = new Player("용사 김코딩");
hero.attack(); // 기본 검 공격
hero.setWeapon(bowStrategy); // 런타임에 활로 변경!
hero.attack();
hero.setWeapon(magicStrategy); // 런타임에 마법으로 변경!
hero.attack();
상태 패턴(State Pattern)은 객체의 내부 상태가 바뀔 때, 객체의 행동(메서드 결과)도 함께 바뀌도록 하는 패턴입니다. 전략 패턴과 구조가 거의 같지만, 목적이 다릅니다.
전자레인지를 생각해봅시다. '정지 상태'에서 시작 버튼을 누르면 가열이 되지만, 이미 '가동 상태'에서 시작 버튼을 누르면 아무 일도 안 하거나 시간이 연장됩니다. 즉, 상태에 따라 if-else 지옥을 만드는 대신 상태 자체를 클래스로 분리하여 캡슐화합니다.
객체의 내부 상태가 바뀔 때 객체의 동작도 함께 바뀌도록 상태를 클래스로 분리하여 위임합니다.
class VendingMachine {
constructor() {
this.noCoinState = new NoCoinState(this);
this.hasCoinState = new HasCoinState(this);
this.currentState = this.noCoinState;
}
setState(state) { this.currentState = state; }
insertCoin() { this.currentState.insertCoin(); }
pushButton() { this.currentState.pushButton(); }
}
class NoCoinState {
constructor(machine) { this.machine = machine; }
insertCoin() {
console.log("동전을 넣었습니다.");
this.machine.setState(this.machine.hasCoinState);
}
pushButton() { console.log("동전을 먼저 넣어주세요."); }
}
class HasCoinState {
constructor(machine) { this.machine = machine; }
insertCoin() { console.log("이미 동전이 있습니다."); }
pushButton() {
console.log("음료수가 나옵니다.");
this.machine.setState(this.machine.noCoinState);
}
}
const machine = new VendingMachine();
machine.pushButton();
machine.insertCoin();
machine.pushButton();
어댑터 패턴(Adapter Pattern)은 서로 호환되지 않는 두 인터페이스(클래스)를 연결하여 함께 동작할 수 있도록 변환기(Adapter) 역할을 제공하는 구조 패턴입니다.
한국의 220V 플러그가 달린 가전제품을 일본에 가져가서 110V 콘센트에 꽂으려면 돼지코(변환 어댑터)가 필요합니다. 소프트웨어에서도 기존에 잘 작성된 레거시 클래스를 수정하지 않고, 새로운 시스템(인터페이스) 규격에 맞춰 끼워넣어야 할 때 매우 강력한 힘을 발휘합니다.
호환되지 않는 인터페이스(Adaptee)를 클라이언트가 기대하는 인터페이스(Target)로 변환(Adapter)해줍니다.
// 1. 클라이언트가 기대하는 동작 (Target)
// JS에는 interface가 없으므로 duck typing을 사용합니다.
// 2. 외부 라이브러리나 기존 시스템 (Adaptee - 220V 가전)
class Appliance220V {
powerOn220V() {
console.log("220V 전원이 공급되어 작동합니다. 위잉~!");
}
}
// 3. 어댑터 클래스 (돼지코)
class SocketAdapter {
constructor(appliance) {
this.appliance = appliance;
}
powerOn110V() {
console.log("어댑터 동작: 110V 입력을 220V로 변환합니다.");
this.appliance.powerOn220V();
}
}
// 4. Client (사용 예시)
function connectToJapanSocket(socket) {
socket.powerOn110V();
}
const koreanHeater = new Appliance220V();
const adapter = new SocketAdapter(koreanHeater);
connectToJapanSocket(adapter);
파사드 패턴(Facade Pattern)은 건물의 웅장한 정면(Facade) 뒤로 복잡한 배관과 전선들이 숨겨져 있듯이, 복잡한 내부 서브시스템들을 뒤로 숨기고 사용하기 쉬운 단순한 통합 인터페이스 하나만을 제공하는 패턴입니다.
영화를 보기 위해 'TV 전원 켜기 -> 조명 어둡게 끄기 -> 스피커 볼륨 조절 -> 넷플릭스 실행' 등 클라이언트가 4개의 클래스를 직접 제어하는 대신, HomeTheaterFacade 클래스에 watchMovie()라는 메서드 하나만 만들어 복잡한 절차를 통합 위임합니다.
파사드 패턴은 복잡한 서브시스템들에 대한 단순화된 인터페이스(Facade)를 제공합니다.
class TV {
on() { console.log("TV 전원 켜기"); }
off() { console.log("TV 전원 끄기"); }
}
class Lighting {
dim() { console.log("조명 어둡게 낮추기"); }
on() { console.log("조명 밝게 켜기"); }
}
class Netflix {
playMovie(title) { console.log(`넷플릭스 '${title}' 재생 시작!`); }
}
// Facade Class
class HomeTheaterFacade {
constructor(tv, lighting, netflix) {
this.tv = tv;
this.lighting = lighting;
this.netflix = netflix;
}
watchMovie(movieTitle) {
console.log("\n--- 영화 볼 준비를 시작합니다 ---");
this.lighting.dim();
this.tv.on();
this.netflix.playMovie(movieTitle);
}
stopMovie() {
console.log("\n--- 영화를 종료합니다 ---");
this.tv.off();
this.lighting.on();
}
}
// Client
const homeTheater = new HomeTheaterFacade(new TV(), new Lighting(), new Netflix());
homeTheater.watchMovie("인셉션");
homeTheater.stopMovie();
추상 팩토리 패턴(Abstract Factory Pattern)은 관련성 있는 여러 객체군(Family)을 생성하기 위한 인터페이스를 제공하는 생성 패턴입니다. 팩토리 메서드가 1개의 객체를 생성한다면, 추상 팩토리는 연관된 '여러 개'의 객체를 세트로 생성합니다.
예를 들어, Mac과 Windows 두 가지 운영체제를 지원하는 UI 라이브러리를 만들 때, 버튼과 체크박스를 섞어서 쓰면 안 됩니다(Windows 버튼 + Mac 체크박스 조합 불가). 추상 팩토리를 사용하면 WinUIFactory를 주입할 경우 알아서 Windows용 세트만 생성되도록 보장할 수 있습니다.
추상 팩토리 패턴은 연관된 객체들의 집합(Family)을 생성하기 위한 인터페이스를 제공합니다.
class WinButton { render() { console.log("Win Button"); } }
class MacButton { render() { console.log("Mac Button"); } }
class WinCheckbox { render() { console.log("Win Checkbox"); } }
class MacCheckbox { render() { console.log("Mac Checkbox"); } }
class WinFactory {
createButton() { return new WinButton(); }
createCheckbox() { return new WinCheckbox(); }
}
class MacFactory {
createButton() { return new MacButton(); }
createCheckbox() { return new MacCheckbox(); }
}
// Client
const factory = new MacFactory();
const button = factory.createButton();
const checkbox = factory.createCheckbox();
button.render(); checkbox.render();
브릿지 패턴(Bridge Pattern)은 추상화(Abstraction)와 구현(Implementation)을 분리하여 두 가지를 독립적으로 확장할 수 있도록 하는 구조 패턴입니다.
리모컨(추상층)과 TV(구현층)를 생각해봅시다. 리모컨의 종류(기본 리모컨, 고급 리모컨)도 다양하게 늘어날 수 있고, TV 브랜드(삼성, LG)도 다양하게 늘어날 수 있습니다. 상속으로만 해결하려면 `SamsungBasicRemote`, `LGAdvancedRemote` 처럼 수많은 클래스가 생성(클래스 폭발)됩니다. 브릿지 패턴은 리모컨 안에 TV 인터페이스를 조립(Composition)시켜 두 계층을 분리하는 다리(Bridge)를 놔줍니다.
브릿지 패턴은 추상화(Abstraction)와 구현(Implementation)을 분리하여 독립적으로 확장할 수 있게 합니다.
class Red {
applyColor() { console.log("빨간색 적용"); }
}
class Blue {
applyColor() { console.log("파란색 적용"); }
}
class Shape {
constructor(color) {
this.color = color;
}
draw() { throw new Error("추상 메서드"); }
}
class Circle extends Shape {
draw() {
process.stdout?.write("원 그리기 -> ") || console.log("원 그리기 ->");
this.color.applyColor();
}
}
class Square extends Shape {
draw() {
process.stdout?.write("정사각형 그리기 -> ") || console.log("정사각형 그리기 ->");
this.color.applyColor();
}
}
const redCircle = new Circle(new Red());
redCircle.draw();
const blueSquare = new Square(new Blue());
blueSquare.draw();
컴포짓 패턴(Composite Pattern)은 객체들을 트리(Tree) 구조로 구성하여 개별 객체(단일 객체)와 복합 객체(그룹)를 클라이언트 입장에서 똑같은 방법으로 다룰 수 있게 해주는 패턴입니다.
가장 완벽한 예시는 파일 시스템입니다. 폴더 안에는 파일이 있을 수도 있고, 또 다른 폴더가 있을 수도 있습니다. 사용자가 폴더의 getSize()를 호출하면 폴더 안의 모든 파일과 하위 폴더의 크기를 재귀적으로 합산합니다. 파일이든 폴더든 똑같은 인터페이스(컴포넌트)로 취급하기 때문에 처리가 매우 단순해집니다.
컴포짓 패턴은 단일 객체와 복합 객체를 동일하게 다룰 수 있도록 트리 구조로 구성합니다.
class File {
constructor(name) { this.name = name; }
showDetails(indent = "") { console.log(`${indent}📄 파일: ${this.name}`); }
}
class Folder {
constructor(name) {
this.name = name;
this.components = [];
}
add(component) { this.components.push(component); }
showDetails(indent = "") {
console.log(`${indent}📁 폴더: ${this.name}`);
for (const c of this.components) c.showDetails(indent + " ");
}
}
const root = new Folder("root");
const docs = new Folder("docs");
docs.add(new File("resume.pdf"));
root.add(docs);
root.add(new File("config.txt"));
root.showDetails();
데코레이터 패턴(Decorator Pattern)은 객체의 뼈대(원본)는 그대로 둔 채, 런타임에 동적으로 객체에 새로운 책임이나 기능(장식)을 유연하게 추가할 수 있는 구조 패턴입니다.
카페에서 '에스프레소'라는 기본 커피 객체에 '물'을 감싸면 아메리카노가 되고, 거기에 다시 '우유'를 감싸면 라떼가 되는 원리입니다. 상속을 통해 `LatteCoffee`, `MochaCoffee` 클래스를 수없이 만드는 대신, 장식자(Decorator)들을 양파 껍질처럼 계속 씌우는 방식으로 결합도를 크게 낮춥니다. Java의 I/O 스트림(`BufferedReader(new FileReader(...))`)이 이 패턴의 대표적인 적용 사례입니다.
데코레이터 패턴은 기존 객체의 코드를 수정하지 않고 동적으로 기능을 확장(장식)할 수 있게 합니다.
class SimpleCoffee {
getCost() { return 10; }
getDescription() { return "일반 커피"; }
}
class MilkDecorator {
constructor(coffee) { this.coffee = coffee; }
getCost() { return this.coffee.getCost() + 2; }
getDescription() { return this.coffee.getDescription() + ", 우유 추가"; }
}
class SugarDecorator {
constructor(coffee) { this.coffee = coffee; }
getCost() { return this.coffee.getCost() + 1; }
getDescription() { return this.coffee.getDescription() + ", 설탕 추가"; }
}
let coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.getDescription(), "/ 가격: $" + coffee.getCost());
플라이웨이트 패턴(Flyweight Pattern)은 수많은 동일한(또는 매우 유사한) 객체들을 생성할 때, 객체 내부의 공통된 데이터를 공유함으로써 메모리 낭비를 극적으로 줄이는 구조 패턴입니다.
마인크래프트 같은 게임에서 수만 개의 '나무 블록'을 그릴 때, 텍스처 이미지나 색상 같은 '변하지 않는 속성(Intrinsic)'은 한 번만 메모리에 올린 뒤 모든 블록이 공유합니다. 그리고 좌표(X,Y,Z) 같은 '각각 다른 속성(Extrinsic)'만 외부에서 받아 처리하여 OutOfMemory(메모리 초과) 에러를 방지합니다.
플라이웨이트 패턴은 본질적(Intrinsic) 상태를 공유하여 수많은 객체를 생성할 때 발생하는 메모리 낭비를 방지합니다.
class TreeType {
constructor(name, color, texture) {
this.name = name; this.color = color; this.texture = texture;
}
draw(x, y) { console.log(`나무 그리기: [${this.name}, ${this.color}] at (${x}, ${y})`); }
}
class TreeFactory {
static treeTypes = {};
static getTreeType(name, color, texture) {
const key = `${name}_${color}_${texture}`;
if (!this.treeTypes[key]) {
this.treeTypes[key] = new TreeType(name, color, texture);
}
return this.treeTypes[key];
}
}
class Tree {
constructor(x, y, type) {
this.x = x; this.y = y; this.type = type;
}
draw() { this.type.draw(this.x, this.y); }
}
const trees = [];
const pineType = TreeFactory.getTreeType("소나무", "초록", "거친질감");
trees.push(new Tree(10, 20, pineType));
trees.push(new Tree(50, 60, pineType));
for (const tree of trees) tree.draw();
프록시 패턴(Proxy Pattern)은 대상 객체에 대한 접근을 제어하거나, 실제 객체가 생성되기 전후로 부가적인 작업(캐싱, 보안 검사, 지연 로딩 등)을 수행하기 위해 대리자(Proxy)를 두는 구조 패턴입니다.
웹 브라우저에서 용량이 큰 고화질 이미지를 로딩할 때, 이미지가 다 다운로드되기 전까지는 프록시 객체가 '로딩 중...'이라는 가짜(또는 저화질) 이미지를 보여주다가 완료되면 진짜 객체에게 렌더링을 위임(Delegate)하는 방식(Virtual Proxy)이 대표적입니다. 이외에도 권한 제어(Protection Proxy)나 캐싱에도 쓰입니다.
프록시 패턴은 실제 객체에 대한 접근을 제어하거나 생성 시점을 지연시키기 위한 대리자(Proxy)를 제공합니다.
class RealImage {
constructor(filename) {
this.filename = filename;
this.loadFromDisk();
}
loadFromDisk() { console.log(`디스크에서 이미지 로딩 중... ${this.filename}`); }
display() { console.log(`이미지 표시: ${this.filename}`); }
}
class ProxyImage {
constructor(filename) { this.filename = filename; this.realImage = null; }
display() {
if (!this.realImage) this.realImage = new RealImage(this.filename);
this.realImage.display();
}
}
const image = new ProxyImage("high_res_photo.jpg");
console.log("--- 아직 로딩 안됨 ---");
image.display(); // 이때 로딩됨
console.log("--- 캐시됨 ---");
image.display();
템플릿 메서드 패턴(Template Method Pattern)은 전체적인 알고리즘의 '뼈대(흐름)'는 부모(추상) 클래스에 정의하고, 단계별 '구체적인 구현'은 자식 클래스에게 위임하는 행위 패턴입니다.
커피와 홍차를 끓이는 과정을 보면 `1. 물 끓이기 -> 2. 우려내기 -> 3. 컵에 따르기 -> 4. 첨가물 넣기` 로 전체 흐름이 완벽히 똑같습니다. 이때 부모 클래스의 makeBeverage() 메서드 안에 이 4단계의 순서를 고정(final)해두고, 자식 클래스(Coffee, Tea)는 2번과 4번 내용만 알맞게 오버라이딩하여 코드 중복을 완전히 제거합니다.
템플릿 메서드 패턴은 알고리즘의 골격을 정의하고 일부 단계를 서브클래스로 연기합니다.
class BeverageRecipe {
prepareRecipe() {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
boilWater() { console.log("물 끓이는 중"); }
pourInCup() { console.log("컵에 따르는 중"); }
brew() { throw new Error("추상 메서드: brew 구현 필요"); }
addCondiments() { throw new Error("추상 메서드: addCondiments 구현 필요"); }
}
class Tea extends BeverageRecipe {
brew() { console.log("찻잎 우려내는 중"); }
addCondiments() { console.log("레몬 추가"); }
}
class Coffee extends BeverageRecipe {
brew() { console.log("커피 내리는 중"); }
addCondiments() { console.log("설탕과 우유 추가"); }
}
console.log("--- 차 준비 ---");
new Tea().prepareRecipe();
console.log("\n--- 커피 준비 ---");
new Coffee().prepareRecipe();
책임 연쇄 패턴(Chain of Responsibility Pattern)은 클라이언트의 요청을 처리할 수 있는 여러 객체들을 하나의 사슬(Chain)로 연결해 두고, 자신이 처리할 수 없으면 다음 객체로 요청을 떠넘기는 행위 패턴입니다.
회사에서 결재를 올릴 때, 100만 원짜리 기안은 '팀장'이 바로 승인하지만, 1000만 원짜리 기안은 팀장이 처리할 권한이 없으므로 '본부장'에게 결재를 넘깁니다. 본부장도 안되면 '사장'에게 넘어가는 다단계 처리 구조를 `if-else` 중첩 없이 유연하게 만들 수 있습니다.
책임 연쇄 패턴은 요청을 보내는 객체와 처리하는 객체를 분리하고, 여러 객체에게 처리 기회를 제공합니다.
class Approver {
constructor(name) { this.name = name; this.next = null; }
setNext(approver) { this.next = approver; return approver; }
processRequest(amount) { throw new Error("구현 필요"); }
}
class Manager extends Approver {
processRequest(amount) {
if (amount <= 1000) console.log(`${this.name}이(가) $${amount} 결제 승인`);
else if (this.next) this.next.processRequest(amount);
}
}
class Director extends Approver {
processRequest(amount) {
if (amount <= 5000) console.log(`${this.name}이(가) $${amount} 결제 승인`);
else if (this.next) this.next.processRequest(amount);
}
}
class CEO extends Approver {
processRequest(amount) {
if (amount <= 10000) console.log(`${this.name}이(가) $${amount} 결제 승인`);
else console.log(`$${amount}은(는) 이사회 승인이 필요합니다.`);
}
}
const manager = new Manager("팀장");
const director = new Director("본부장");
const ceo = new CEO("대표이사");
manager.setNext(director).setNext(ceo);
manager.processRequest(500);
manager.processRequest(3000);
manager.processRequest(8000);
manager.processRequest(15000);
커맨드 패턴(Command Pattern)은 요청(명령) 자체를 객체로 캡슐화하여, 메서드 인자로 전달하거나, 큐(Queue)에 저장해 순차적으로 실행하거나, 심지어 실행 취소(Undo) 기능을 구현할 수 있게 해주는 행위 패턴입니다.
스마트홈 앱에서 하나의 버튼에 'TV 켜기', '조명 끄기', '에어컨 켜기' 등 여러 기능을 자유롭게 매핑하고 싶다면 버튼 클래스 안에 기기 제어 코드를 하드코딩해서는 안 됩니다. 명령(Command) 객체를 만들어 버튼에 꽂아주면, 버튼은 단지 command.execute()만 호출하는 바보(단순한 Invoker)가 되어 극도의 유연성을 확보할 수 있습니다.
커맨드 패턴은 요청을 객체로 캡슐화하여, 요청 내역을 매개변수화하거나 큐에 저장할 수 있게 합니다.
class Light {
on() { console.log("조명 ON"); }
off() { console.log("조명 OFF"); }
}
class LightOnCommand {
constructor(light) { this.light = light; }
execute() { this.light.on(); }
}
class LightOffCommand {
constructor(light) { this.light = light; }
execute() { this.light.off(); }
}
class RemoteControl {
setCommand(command) { this.command = command; }
pressButton() { this.command.execute(); }
}
const light = new Light();
const lightOn = new LightOnCommand(light);
const lightOff = new LightOffCommand(light);
const remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton();
remote.setCommand(lightOff);
remote.pressButton();
반복자 패턴(Iterator Pattern)은 배열(Array), 리스트(List), 해시맵(Map) 등 데이터가 저장된 내부 구조나 원리를 모르더라도 집합 객체 안의 모든 원소들을 통일된 방법으로 차례대로 접근(순회)할 수 있게 해주는 행위 패턴입니다.
Java의 java.util.Iterator (hasNext(), next())가 바로 이 패턴의 구현체입니다. 배열은 `for(int i=0; i
반복자 패턴은 컬렉션의 내부 구조를 노출하지 않고 그 요소들을 순차적으로 접근할 수 있는 방법을 제공합니다.
class Book {
constructor(name) { this.name = name; }
}
class BookShelf {
constructor() { this.books = []; }
addBook(book) { this.books.push(book); }
getBookAt(index) { return this.books[index]; }
getLength() { return this.books.length; }
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.books.length) return { value: this.books[index++], done: false };
else return { done: true };
}
};
}
}
const bookShelf = new BookShelf();
bookShelf.addBook(new Book("Clean Code"));
bookShelf.addBook(new Book("Design Patterns"));
bookShelf.addBook(new Book("Refactoring"));
for (const book of bookShelf) {
console.log(book.name);
}
중재자 패턴(Mediator Pattern)은 객체들 간의 복잡한 상호작용을 캡슐화하여, 객체들이 서로 직접 통신하지 않고 '중재자'를 통해서만 통신하도록 만드는 행위 패턴입니다.
공항의 비행기들을 생각해봅시다. 수많은 비행기들이 서로의 위치를 공유하며 직접 소통하면 통신망이 거미줄처럼 엉켜 대형 사고가 납니다. 대신 '관제탑(Mediator)' 하나를 두고, 비행기들은 오직 관제탑과만 통신합니다. 채팅방, 스마트홈 허브 등 M:N의 복잡한 관계를 1:N으로 단순화할 때 필수적인 패턴입니다.
중재자 패턴은 객체 간의 혼란스러운 의존 관계들을 줄여줍니다. 객체들이 직접 서로 통신하는 것을 제한하고, 중재자 객체를 통해서만 협력하도록 합니다.
class ChatRoom {
static showMessage(user, message) {
console.log(`[${new Date().toLocaleTimeString()}] ${user.name}: ${message}`);
}
}
class User {
constructor(name) { this.name = name; }
sendMessage(message) { ChatRoom.showMessage(this, message); }
}
const john = new User("John");
const jane = new User("Jane");
john.sendMessage("Hi Jane!");
jane.sendMessage("Hello John!");
메멘토 패턴(Memento Pattern)은 객체의 캡슐화를 파괴하지 않고 객체의 내부 상태를 추출하여 저장(Snapshot)해 두었다가, 나중에 객체를 그 상태로 복구(Restore)할 수 있게 해주는 행위 패턴입니다.
우리가 에디터에서 자주 쓰는 Ctrl+Z (실행 취소)가 정확히 메멘토 패턴입니다. 게임의 '세이브/로드' 시스템도 마찬가지입니다. 상태를 저장하는 객체(Originator)가 자신의 상태를 담은 암호 상자(Memento)를 만들어 관리인(Caretaker)에게 맡겨두고, 필요할 때 상자를 돌려받아 과거로 회귀합니다.
메멘토 패턴은 객체의 캡슐화를 파괴하지 않고 객체의 내부 상태를 저장하고 복원할 수 있게 합니다.
class Memento {
constructor(state) { this.state = state; }
getState() { return this.state; }
}
class Originator {
setState(state) { this.state = state; }
getState() { return this.state; }
save() { return new Memento(this.state); }
restore(memento) { this.state = memento.getState(); }
}
class Caretaker {
constructor() { this.mementos = []; }
add(memento) { this.mementos.push(memento); }
get(index) { return this.mementos[index]; }
}
const originator = new Originator();
const caretaker = new Caretaker();
originator.setState("상태 1");
originator.setState("상태 2");
caretaker.add(originator.save());
originator.setState("상태 3");
caretaker.add(originator.save());
originator.setState("상태 4");
console.log("현재 상태:", originator.getState());
originator.restore(caretaker.get(0));
console.log("복원된 상태 (1번째 저장점):", originator.getState());
방문자 패턴(Visitor Pattern)은 객체의 데이터 구조와 그 구조를 처리하는 연산(동작)을 완벽하게 분리하는 행위 패턴입니다.
대형 쇼핑몰 장바구니에 '가전제품', '신선식품', '주류'가 들어있다고 해봅시다. 만약 '할인액 계산', '세금 계산', '배송비 계산' 로직을 각 상품 클래스 안에 넣으면 클래스가 비대해집니다. 방문자 패턴은 상품(데이터 구조)은 accept()라는 문만 열어두고, 별도의 방문자 클래스(TaxVisitor, DiscountVisitor)가 문을 열고 들어가 알아서 로직을 처리하게 만듭니다. OCP(개방 폐쇄 원칙)를 극대화합니다.
방문자 패턴은 객체 구조를 변경하지 않고도 객체들에 대해 새로운 연산을 수행할 수 있게 합니다.
class ConcreteElementA {
accept(visitor) { visitor.visitElementA(this); }
operationA() { return "ElementA Operation"; }
}
class ConcreteElementB {
accept(visitor) { visitor.visitElementB(this); }
operationB() { return "ElementB Operation"; }
}
class ConcreteVisitor1 {
visitElementA(element) { console.log(`Visitor1: ${element.operationA()}`); }
visitElementB(element) { console.log(`Visitor1: ${element.operationB()}`); }
}
const elements = [new ConcreteElementA(), new ConcreteElementB()];
const visitor1 = new ConcreteVisitor1();
for (const el of elements) {
el.accept(visitor1);
}
인터프리터 패턴(Interpreter Pattern)은 특정 언어의 문법(문장, 표현식)을 정의하고, 그 언어로 작성된 문장을 해석(평가)하는 엔진을 만드는 행위 패턴입니다.
정규표현식 엔진이나, SQL 파서, 혹은 컴파일러 내부에서 사용됩니다. 문법 규칙을 추상 구문 트리(AST, Abstract Syntax Tree) 형태의 클래스 계층으로 모델링하여 해석합니다. 성능 이슈와 복잡성 때문에 실무에서 직접 웹 개발에 쓰이는 경우는 거의 없지만, DSL(Domain Specific Language)을 만들 때 핵심적인 역할을 합니다.
인터프리터 패턴은 언어의 문법을 정의하고 그 언어로 작성된 문장을 해석하는 방법을 제공합니다.
class Context {
constructor(input) { this.input = input; this.output = 0; }
}
class Expression {
interpret(context) { throw new Error("구현 필요"); }
}
class TerminalExpression extends Expression {
interpret(context) {
if (context.input.includes("A")) context.output += 1;
if (context.input.includes("B")) context.output += 2;
}
}
const context = new Context("A B");
const exp = new TerminalExpression();
exp.interpret(context);
console.log("결과:", context.output);