- 익숙한 패턴, class 의 인스턴스가 오직 하나만 존재하고 static 하게 접근 하여 가져온다.
- singleton 은 객체가 단 하나만 존재하여, shared resource 에 access 를 통제 할 수 있고 그 객체에 대해 global access point 를 제공 한다.
- 생성자는 private 으로 가리고, static method 가 생성자 역할을 대신 하여, 이 private 생성자를 최초 1번 생성하고, private static 변수에 저장해 두고, 호출 될 때마다 이를 return 한다.
- 편하고 좋으나, design 원칙입장에선 anti pattern 이며 multithread 환경에서는 특별히 처리 해줘야 한다는 것, unit test 를 하기가 어렵다는 것 등이 단점이다.
- 아래 예제의 경우, multithread 환경에서, 두개의 singleton 이 생성되는 것을 막기 위해 volatile 과 synchronized 를 사용했다. 이렇게 사용해 본적은 없는거 같은데, 앞으로 쓰게 되면 multithread 환경도 항상 고려해야하겠다.
public final class Singleton {
// The field must be declared volatile so that double check lock would work
// correctly.
private static volatile Singleton instance;
public String value;
private Singleton(String value) {
this.value = value;
}
public static Singleton getInstance(String value) {
// The approach taken here is called double-checked locking (DCL). It
// exists to prevent race condition between multiple threads that may
// attempt to get singleton instance at the same time, creating separate
// instances as a result.
//
// It may seem that having the `result` variable here is completely
// pointless. There is, however, a very important caveat when
// implementing double-checked locking in Java, which is solved by
// introducing this local variable.
//
// You can read more info DCL issues in Java here:
// https://refactoring.guru/java-dcl-issue
Singleton result = instance;
if (result != null) {
return result;
}
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton(value);
}
return instance;
}
}
}
Comments
Post a Comment