Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- ubuntu
- prototype pattern
- $event.target.value
- MVVM
- Spring Boot
- kebab case
- mount point
- Singleton pattern
- Python
- Factory Method Pattern
- v-show vs v-if
- vuejs
- v-model vs v-bind
- IPv6
- click.native
- Linux
- data
- builder pattern
- design pattern
- executable jar
- zen of python
- camel case error
- maven
- java
Archives
- Today
- Total
Eddie's Blog
[design pattern] Singleton Pattern 본문
유형: 생성자 패턴
클래스의 인스턴스가 하나임을 보장하고 전역적 접근을 허용하게 한다.
1. static 키워드를 통한 instance 즉시 생성
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
public static EagerInitializedSingleton getInstance() {
return instance;
}
private EagerInitializedSingleton() {}
/* more methods */
}
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
static {
try {
instance = new StaticBlockSingleton();
} catch (Exception e) {
throw new RuntimeException("Failed to instantiate.");
}
}
private StaticBlockSingleton() {}
/* more methods */
}
2. instance 호출 시점에 instance 존재 여부를 확인하고 생성
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
public static LazyInitializedSingleton getInstance() {
if (instance == null) {
instance = new LazyInitializedSingleton();
}
}
private LazyInitializedSingleton() {}
/* more methods */
}
3. 동시성을 위한 Thread Safe한 Singleton
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
public static synchronized ThreadSafeSingleton getInstance() {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
// 인스턴의 존재를 두 번 점검하고 생성 시점을 동기화하는 Double Checked-Locking
public static ThreadSafeSingleton getInstanceWithDoubleCheckedLocking() {
if (instance == null) {
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
private ThreadSafeSingleton() {}
/* more methods */
}
DCL(Double Checked-Locking)은 메모리 문제, Race Condition 등에 대한 이슈로 문제가 지적 되고 있어 올바른 동작을 보장 받지 못한다는 것이 정설이다. 이를 극복하기 위해 Peter Haggar는 volatile 등을 활용하는 방식을 제시하고 있다. https://www.ibm.com/developerworks/library/j-dcl/index.html
4. Enum 을 활용한 Singleton
public enum EnumSingleton {
INSTANCE;
public static void doSomething(){
/* more codes */
}
}
'programmings' 카테고리의 다른 글
[design pattern] Prototype Pattern (0) | 2019.03.28 |
---|---|
[design pattern] Factory Method Pattern (0) | 2019.03.28 |
[design pattern] Builder Pattern (0) | 2019.03.28 |
[design pattern] Abstract Factory Pattern (0) | 2019.03.28 |
[spring boot] How to package a project with shell-executable jar (0) | 2019.02.11 |
Comments