GoF (Gang of Four) 디자인 패턴
작성일 : 2025.01.07
1. 생성 패턴 (Creational Patterns)
1.1 싱글톤 패턴 (Singleton)
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
- 사용 사례: 데이터베이스 연결 관리, 로깅, 환경설정 등
- 장점: 리소스 절약, 전역 상태 관리 용이
- 단점: 단위 테스트 어려움, 전역 상태로 인한 복잡성
1.2 추상 팩토리 패턴 (Abstract Factory)
public interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
public class WindowsFactory implements GUIFactory {
public Button createButton() { return new WindowsButton(); }
public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
public class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
- 사용 사례: 크로스 플랫폼 UI 컴포넌트, DB 연결 관리자
- 장점: 제품군 일관성 보장, 구체적 클래스 분리
- 단점: 새로운 제품 추가 시 인터페이스 수정 필요
1.3 빌더 패턴 (Builder)
public class Computer {
private String CPU;
private String RAM;
private String storage;
public static class Builder {
private Computer computer = new Computer();
public Builder CPU(String cpu) {
computer.CPU = cpu;
return this;
}
public Builder RAM(String ram) {
computer.RAM = ram;
return this;
}
public Builder storage(String storage) {
computer.storage = storage;
return this;
}
public Computer build() {
return computer;
}
}
}
- 사용 사례: 복잡한 객체의 단계별 생성
- 장점: 객체 생성 과정의 유연한 변경 가능
- 단점: 코드 복잡성 증가
1.4 프로토타입 패턴 (Prototype)
public interface Cloneable {
Cloneable clone();
}
public class ConcretePrototype implements Cloneable {
private String field;
public Cloneable clone() {
ConcretePrototype clone = new ConcretePrototype();
clone.field = this.field;
return clone;
}
}
- 사용 사례: 객체 복사가 생성보다 효율적일 때
- 장점: 복잡한 객체 생성 비용 감소
- 단점: 순환 참조 처리 필요
1.5 팩토리 메서드 패턴 (Factory Method)
public abstract class Creator {
abstract Product factoryMethod();
public void anOperation() {
Product product = factoryMethod();
product.operation();
}
}
public class ConcreteCreator extends Creator {
public Product factoryMethod() {
return new ConcreteProduct();
}
}
- 사용 사례: 프레임워크에서의 객체 생성
- 장점: 객체 생성의 유연성 제공
- 단점: 클래스 수 증가
2. 구조 패턴 (Structural Patterns)
2.1 어댑터 패턴 (Adapter)
public interface Target {
void request();
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
- 사용 사례: 외부 라이브러리 통합, 레거시 시스템 연동
- 장점: 호환성 문제 해결
- 단점: 추가 코드 작성 필요
2.2 브리지 패턴 (Bridge)
public abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
abstract public void operation();
}
public interface Implementor {
void operationImpl();
}
- 사용 사례: 플랫폼 독립적인 GUI
- 장점: 추상화와 구현의 분리
- 단점: 복잡성 증가