필기 단일 디자인 모드
1. 즉시 불 러 오기
즉시 불 러 오 는 것 은 클래스 를 사용 할 때 대상 을 만 들 었 습 니 다.
장점: 간단 하고 다 중 스 레 드 동기 화 문제 가 없습니다.
단점: 인 스 턴 스 가 사용 되 지 않 았 을 때 대상 은 이 공간 을 차지 합 니 다.
public class Singleton {
// , static、final
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2. getInstance () 의 성능 이 응용 프로그램 에 중요 하지 않다 면
getInstance () 에 synchronized 키 워드 를 추가 하고 게 으 름 피 우기
public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){
//
public static synchronized Singletion getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
3. 로드 지연 이 아 닌 방법.
JVM 은 모든 스 레 드 가 유 니 크 인 스 턴 스 변 수 를 방문 하도록 보장 하기 전에 이 인 스 턴 스 를 만 듭 니 다.
public class Singleton{
private static Singleton uniqueInstance
= new Singleton();
private Singleton(){}
public static Singletion getInstance(){
return uniqueInstance;
}
}
4. 이중 검사 에 잠 금 을 추가 하고 getInstance () 에서 동기 화 사용 을 감소 합 니 다.
volatile + synchronized + 로드 지연, 성능 이 가장 좋 습 니 다: getInstance () 의 시간 을 크게 줄 입 니 다.
public class Singleton{
private volatile static Singleton uniqueInstance;
private Singleton(){
// , ,
//
public static Singletion getInstance(){
if(uniqueInstance == null){
Synchronized(Singleton.class){
// , 。 null,
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
단일 모드 의 특징
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Android 디자인 모드 의 단일 예 모드 Singleton하나의 예 는 자신 이 하나의 인 스 턴 스 를 만 들 수 있 고 자주 만 들 거나 소각 할 필요 가 없 으 며 메모리 가 대상 의 접근 속 도 를 가속 화 할 수 있 습 니 다. 게으름뱅이 모드 는 외부 대상 이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.