728x90
반응형
싱글턴 패턴은 class 인스턴스를 하나만 만들고, 그 인스턴스로의 전역 접근을 제어하는 패턴이다. 전역변수처럼 사용 가능하지만 전역볏누와 다르게 객체를 필요할 때만 만들기 때문에 자원의 낭비가 덜하다. 연결 pool , Thread pool 같은 자원 pool관리에 이점이 있다.
- 고전 싱글턴 패턴 구현
public class Singleton
{
private static Singleton uniqueInstance; ------> a
private Singleton(){} ------> b
public static Signleton getInstance()
{
if(uniqueInstance == null){
uniqueInstance = new Singleton(); ------> c
}
return uniqueIntance; ------> d
}
}
하지만 멀티스레드인 경우 시간이 어긋나게 되면 서로 다른 인스턴스 2개가 생성되어 싱글턴 패턴이 아니게 된다.
이는 synchronized를 사용하여 동기화 시켜 위와 같은 상황을 막아준다.
public class Singleton
{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Signleton getInstance()
{
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueIntance;
}
}
간단한 예제는 git!
728x90
반응형
'Computer Science > 디자인패턴' 카테고리의 다른 글
Adapter Pattern (0) | 2022.10.18 |
---|---|
Command Pattern (0) | 2022.09.28 |
Factory / Factory Abstract Method Pattern (0) | 2022.09.13 |
Decorator Pattern (0) | 2022.09.06 |
Observer Pattern (0) | 2022.08.30 |