Christmas Pikachu 싱글톤 패턴
개발일지/디자인 패턴

싱글톤 패턴

ZI_CO 2023. 12. 17.

 

1. Eager Initialization:
 *    - 클래스 로딩 시점에 객체를 미리 생성하여 인스턴스를 제공하는 방법.
 *    - 자원을 미리 소비할 수 있고, 멀티스레드 환경에서 안전하지만 자원 낭비의 가능성이 있다.

 1. Eager Initialization
class EagerInitializedSingleton {
    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

    private EagerInitializedSingleton() {
        // private 생성자로 외부에서 객체 생성 방지
    }

    public static EagerInitializedSingleton getInstance() {
        return instance;
    }
}

 

 

 

2. Static Block Initialization:
 *    - 클래스 로딩 시점에 객체를 생성하는데, 정적 블록을 활용하여 예외 처리 가능.
 *    - Eager Initialization과 비슷하게 자원을 미리 소비하며 자원 낭비의 가능성이 있다.

// 2. Static Block Initialization
class StaticBlockSingleton {
    private static final StaticBlockSingleton instance;

    static {
        try {
            instance = new StaticBlockSingleton();
        } catch (Exception e) {
            throw new RuntimeException("Exception occurred in creating singleton instance");
        }
    }

    private StaticBlockSingleton() {
        // private 생성자로 외부에서 객체 생성 방지
    }

    public static StaticBlockSingleton getInstance() {
        return instance;
    }
}


 *
 * 3. Lazy Initialization:
 *    - 객체가 필요한 시점에 생성하는 방법.
 *    - 자원 효율성 증가하지만 멀티스레드 환경에서 동기화 문제가 발생할 수 있다.

// 3. Lazy Initialization
class LazyInitializedSingleton {
    private static LazyInitializedSingleton instance;

    private LazyInitializedSingleton() {
        // private 생성자로 외부에서 객체 생성 방지
    }

    public static LazyInitializedSingleton getInstance() {
        if (instance == null) {
            instance = new LazyInitializedSingleton();
        }
        return instance;
    }
}


 *
 * 4. Thread Safe Singleton:
 *    - Lazy Initialization에서 동기화를 통해 멀티스레드 환경에서 안전하게 객체 생성.
 *    - 하지만 동기화로 인한 성능 저하가 있을 수 있다.

// 4. Thread Safe Singleton
class ThreadSafeSingleton {
    private static ThreadSafeSingleton instance;

    private ThreadSafeSingleton() {
        // private 생성자로 외부에서 객체 생성 방지
    }

    public static synchronized ThreadSafeSingleton getInstance() {
        if (instance == null) {
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
}


 *
 * 5. Bill Pugh Singleton Implementation:
 *    - Inner Static Helper Class를 사용한 방법으로 현재 널리 사용되는 방법.
 *    - 클래스가 로딩될 때는 객체 생성되지 않고, getInstance() 호출 시에만 객체 생성하여 멀티스레드에서도 안전하게 사용 가능.

// 5. Bill Pugh Singleton Implementation
class BillPughSingleton {
    private BillPughSingleton() {
        // private 생성자로 외부에서 객체 생성 방지
    }

    private static class SingletonHelper {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}


 *
 * 6. Enum Singleton:
 *    - Effective Java에서 권장하는 방법으로 가장 간단하고 안전한 방법.
 *    - 멀티스레드에서도 문제 없이 사용 가능하며, Reflection 공격에도 안전하다.
 *
 * 주의: Reflection을 사용하면 몇 가지 방법에서는 싱글톤 보장이 어려울 수 있다.
 */

// 6. Enum Singleton
enum EnumSingleton {
    INSTANCE;

    public void doSomething() {
        // 싱글톤 객체의 동작
    }
}

 

 

 

 

/**
 * 메인 클래스
 */
public class Main {
    public static void main(String[] args) {
        // 각각의 싱글톤 객체를 사용하는 예시
        EagerInitializedSingleton eagerSingleton = EagerInitializedSingleton.getInstance();
        StaticBlockSingleton staticBlockSingleton = StaticBlockSingleton.getInstance();
        LazyInitializedSingleton lazySingleton = LazyInitializedSingleton.getInstance();
        ThreadSafeSingleton threadSafeSingleton = ThreadSafeSingleton.getInstance();
        BillPughSingleton billPughSingleton = BillPughSingleton.getInstance();
        EnumSingleton enumSingleton = EnumSingleton.INSTANCE;

        // 출력 예시
        System.out.println("Eager Singleton: " + eagerSingleton);
        System.out.println("Static Block Singleton: " + staticBlockSingleton);
        System.out.println("Lazy Singleton: " + lazySingleton);
        System.out.println("Thread Safe Singleton: " + threadSafeSingleton);
        System.out.println("Bill Pugh Singleton: " + billPughSingleton);
        System.out.println("Enum Singleton: " + enumSingleton);
    }
}

'개발일지 > 디자인 패턴' 카테고리의 다른 글

싱글톤 패턴 구현 방법  (1) 2024.11.18

댓글