본문 바로가기

Develop/Design Pattern

[Design Pattern] 싱글톤 (Singleton) 패턴

728x90

1. 개요

  • 싱글톤 디자인 패턴 (Singleton Design Pattern)은 특정 클래스의 객체가 단 한 번만 생성되고, 그 객체에 대한 전역적인 접근 지점을 제공하는 디자인 패턴이다.

2. 상황

  • 한 클래스의 인스턴스가 오직 하나만 필요한 경우
  • 그 인스턴스에 대한 전역적인 접근이 필요한 경우
  • 공유된 자원에 대한 중앙 집중적인 제어가 필요한 경우

3. 다이어그램

Singleton

3.1. 설명

  • Singleton 클래스의 생성자는 private 으로 외부에서 사용될 수 없다.
  • private 의 정적 변수 instance 가 존재한다.
  • public 의 정적 메소드 getInstance() 를 통해 instancenull 이 아닌 값이 존재하면 그것을 반환하고, 그렇지 않으면 객체를 새로 생성하여 instance 변수를 초기화한 후 그 객체를 반환한다.

4. 구현

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

  public static Singleton getInstance() { return instance; }
}
public class Client {
  public static void main(String[] args) {
    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();
  }
}

5. 예시

public class Counter {
  private static final Counter instance = new Counter();
  private Counter() {}

  public static Counter getInstance() { return instance; }

  private int value;
  public void increase(int delta) { value += delta; }
  public void decrease(int delta) { value -= delta; }

  public void printValue() { System.out.println("Value: " + value); }
}
public class Client {
  public static void main(String[] args) {
    Counter counter1 = Counter.getInstance();
    System.out.println("\nCounter1: " + counter1);
    counter1.printValue();
    counter1.increase(3);
    System.out.println("After increase 3...");
    counter1.printValue();

    Counter counter2 = Counter.getInstance();
    System.out.println("\nCounter2: " + counter2);
    counter2.printValue();
    counter2.decrease(2);
    System.out.println("After decrease 2...");
    counter2.printValue();
  }
}

실행결과

Counter1: Counter@7ad041f3
Value: 0
After increase 3...
Value: 3

Counter2: Counter@7ad041f3
Value: 3
After decrease 2...
Value: 1

6. 장단점

6.1. 장점

  • 유일 객체를 보장할 수 있다.
  • 객체에 전역적으로 접근 가능하다.

6.2. 장점

  • 코드의 복잡성이 증가한다.
  • 모두가 객체를 사용할 때 혼란을 야기할 수 있다.
  • 테스트가 어려울 수 있다.

관련 포스팅

728x90