본문 바로가기

Programming/Design Pattern

Singleton Pattern

1. 정의

 1) 클래스가 한 개의 인스턴스만을 만들 수 있도록 하고, 어디서나 생성된 인스턴스에 접근할 수 있도록 함

 

2. 문제

 1) 여러 객체가 생성되면 상태 관리가 어려움

 예) 중앙 난방 관리 클래스가 있는데, 이를 여러 객체를 생성하여 중앙 난방을 관리하게 되면 관리가 어려워진다.

 

3. 해결방안

 1) 클래스의 인스턴스를 하나만 생성하도록 한다.

 

4. 사용 예제

 1) 초콜렛 보일러 관리 클래스

  1-1) 일반적인 싱글턴 버전

public class ChocolateBoiler {
  private static ChocolateBoiler uniqueInstance;
  private boolean empty;
  private boolean boiled; 

  private ChocolateBoiler() {
    empty = true; // 보일러가 비어있을 때만  동작
    boiled = false;
  } 
 
  public static ChocolateBoiler getInstance() {
    if (uniqueInstance == null) {
      uniqueInstance = new ChocolateBoiler();
    }
    return uniqueInstance;
  }
  // 나머지 멤버 함수 코드
}

 

  1-2) Thread-safe 버전의 싱글턴

   - 여러 개의 스레드에서 앞에서 작성한 코드가 사용되면 문제가 발생할 수 있음 -> 동기화 필요(synchronized)

   - 문제 : 비효율적일 수 있음(느려질 수 있음)

public class Singleton {
  private static Singleton uniqueInstance;

  private Singleton() { }
  public static synchronized Singleton getInstance() {
    if (uniqueInstance == null) {
      uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
  // 나머지 멤버 함수 코드
}

 

  1-3) 인스턴스를 필요할 때 생성하지 말고, 프로그램 시작될 때 생성

   - volatile : Java 변수를 Main Memory에 저장하겠다라는 것을 명시하는 것입니다.

public class Singleton {
  private volatile static Singleton inst = new Singleton();
  private Singleton() { }
  public static Singleton getInstance() {
    if (inst == null) {
      synchronized (Singleton.class) {
        if (inst == null) {
          inst = new Singleton();
        }
      }
    }
    return inst;
  }
  // 나머지 멤버 함수 코드

'Programming > Design Pattern' 카테고리의 다른 글

Command Pattern 과제  (0) 2019.12.31
Command Pattern  (0) 2019.12.31
Factory Pattern  (0) 2019.12.27
Decorator Pattern 과제  (0) 2019.12.27
Decorator Pattern  (0) 2019.12.27