[Java] 객체 생성 패턴

김선형·2025년 9월 6일

Java

목록 보기
11/27

개요

객체 생성 패턴 (Creational Patterns)는 객체의 생성 과정을 추상화하여, 시스템이 구체적인 클래스에 의존하지 않고 객체를 만들 수 있게 해주는 패턴이다.

종류

Singleton

시스템 전체에서 단 하나의 인스턴스만을 제공하며, 이를 어디서든 접근할 수 있도록 보장한다. Runtime, Logger 등 전역에서 하나의 객체만 필요할 때 사용한다.

public class Singleton {
    private static final Singleton instance = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return instance;
    }
}

장단점

  • 장점: 메모리 절약, 전역 상태 공유, 인스턴스 생명주기 관리 용이
  • 단점: 테스트 어려움, 과도한 공유로 인한 결합도 증가, 멀티스레드 환경에서의 동기화 필요성

Factory Method

객체 생성 코드를 별도의 팩토리 메서드에 위임하며, 객체 생성 로직을 분리한다. 상위 클래스는 인터페이스만 제공하고, 하위 클래스가 생성을 결정한다.

abstract class ProductFactory {
    public abstract Product createProduct();
}

class ConcreteProductFactory extends ProductFactory {
    @Override
    public Product createProduct() {
        return new ConcreteProduct();
    }
}

장단점

  • 장점: 코드의 결합도 감소, 확장성 및 유지보수성 증가
  • 단점: 클래스 수 증가, 코드 구조 복잡성 증가 가능성

Abstract Factory

관련성 있는 여러 종류의 객체 집합을 생성하는 인터페이스를 제공한다.

interface GUIFactory {
    Button createButton();
    Checkbox createCheckbox();
}

class WindowsFactory implements GUIFactory { ... }
class MacFactory implements GUIFactory { ... }

장단점

  • 장점: 관련된 객체들을 일관되게 생성, 쉬운 객체군 교체
  • 단점: 새로운 제품 추가의 어려움, 구조 복잡성 증가 가능성

Builder

복잡한 객체를 단계별로 생성할 수 있게 도와준다. 각 단계는 메서드 체이닝 방식으로 구현할 수 있다,

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();

장단점

  • 장점: 객체 생성 과정 분리, 불변 객체 생성 가능, 가독성 향상
  • 단점: 클래스 구조 복잡성 증가 가능성

Prototype

기존 객체를 복사해 새 객체를 생성한다.

class Product implements Cloneable {
    private String name;
    
    public Product clone() throws CloneNotSupportedException {
        return (Product) super.clone();
    }
}

장단점

  • 장점: 복잡한 객체의 생성 비용 절감, 다양한 객체의 복제 용이
  • 단점: clone() 구현의 복잡성, 깊은 복사/얕은 복사 이슈
profile
선형의 비선형적 기록 🐜

0개의 댓글