객체 생성 패턴 (Creational Patterns)는 객체의 생성 과정을 추상화하여, 시스템이 구체적인 클래스에 의존하지 않고 객체를 만들 수 있게 해주는 패턴이다.
시스템 전체에서 단 하나의 인스턴스만을 제공하며, 이를 어디서든 접근할 수 있도록 보장한다. Runtime, Logger 등 전역에서 하나의 객체만 필요할 때 사용한다.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
객체 생성 코드를 별도의 팩토리 메서드에 위임하며, 객체 생성 로직을 분리한다. 상위 클래스는 인터페이스만 제공하고, 하위 클래스가 생성을 결정한다.
abstract class ProductFactory {
public abstract Product createProduct();
}
class ConcreteProductFactory extends ProductFactory {
@Override
public Product createProduct() {
return new ConcreteProduct();
}
}
관련성 있는 여러 종류의 객체 집합을 생성하는 인터페이스를 제공한다.
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
class WindowsFactory implements GUIFactory { ... }
class MacFactory implements GUIFactory { ... }
복잡한 객체를 단계별로 생성할 수 있게 도와준다. 각 단계는 메서드 체이닝 방식으로 구현할 수 있다,
class User {
private String name;
private int age;
// ...
public static class Builder {
private String name;
private int age;
public Builder setName(String name) { this.name = name; return this; }
public Builder setAge(int age) { this.age = age; return this; }
public User build() { return new User(this); }
}
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
}
// 사용: new User.Builder().setName("Alice").setAge(20).build();
기존 객체를 복사해 새 객체를 생성한다.
class Product implements Cloneable {
private String name;
public Product clone() throws CloneNotSupportedException {
return (Product) super.clone();
}
}
clone() 구현의 복잡성, 깊은 복사/얕은 복사 이슈