자바 단일 모드 의 몇 가지 쓰기
7472 단어 자바
package oop;
/** * * * @author lunatictwo */
public class Singleton {
private final static Singleton instance = new Singleton();
private static boolean isInit = false;
// , instance
private Singleton() {
super();
}
private void init() {
//
}
//
public static synchronized Singleton getInstance() {
if (isInit) {
return instance;//
}
instance.init();// , ,
isInit = true;
return instance;
}
}
이 때 단일 인 스 턴 스 를 가 져 올 때 getInstance()를 통 해서 만 가 져 올 수 있 습 니 다.
업데이트:(2016-01-23):헷 갈 리 지 않도록 오늘 몇 가지 다른 문법 을 추가 합 니 다.
위 에 쓰 인 사례 는 굶 주 린 사람 모드 의 동기 화 안전 표기 법 에 속 합 니 다.대상 을 사용 하기 전에 초기 화 시 켜 대상 이 굶 어 죽지 않도록 하 는 것 입 니 다.지금 은 게으름뱅이 모드 의 사례 를 붙 입 니 다.
package oop;
/** * LazySingleton * * @author lunatictwo * */
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
super();
}
public static LazySingleton getInstance() {
if (null == instance) {
instance = new LazySingleton();
}
return instance;
}
}
스 레 드 가 안전 하지 않다 고 생각 되면 동기 화 자 물 쇠 를 추가 하 십시오.
package oop;
/** * LazySingleton * * @author lunatictwo * */
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
super();
}
public static synchronized LazySingleton getInstance() {//
if (null == instance) {
instance = new LazySingleton();
}
return instance;
}
}
또한 효율 을 높이 기 위해 대상 을 만 들 때 만 잠 금 동기 화(이중 검사)를 추가 할 수 있 습 니 다.그러나 이 모델 은 다음 과 같 습 니 다.
package oop;
/** * DoubleCheckSingleton * * @author lunatictwo * */
public class DoubleCheckSingleton {
private static DoubleCheckSingleton instance = null;
private DoubleCheckSingleton() {
super();
}
public static synchronized DoubleCheckSingleton getInstance() {
if (null == instance) {
synchronized (DoubleCheckSingleton.class) {
if (null == instance) {
instance = new DoubleCheckSingleton();
}
}
}
return instance;
}
}
그러나 이 쓰기 에는 위험 이 존재 합 니 다.두 스 레 드 가 대상 인 스 턴 스 를 초기 화 할 때 대상 을 초기 화 하 는 데 시간 이 필요 하기 때문에 첫 번 째 스 레 드 가 대상 주 소 를 만 든 후(완전히 만 들 지 않 았 을 때)두 번 째 스 레 드 는 대상 이 이미 존재 한다 고 판단 하기 때문에 대상 인 스 턴 스 를 직접 되 돌려 줍 니 다.그러나 두 번 째 스 레 드 에 있어 서 이 대상 의 인 스 턴 스 는 완전히 초기 화 되 지 않 았 다.그래서 이런 글 씨 는 추천 하지 않 습 니 다.
사실 가장 좋 은 문법 은 내부 클래스 를 사용 하 는 것 이다.라인 안전 도 할 수 있 고 문법 도 간단 하 다.다음 과 같다.
package oop;
/** * InternalClassSingleton * * @author lunatictwo * */
public class InternalClassSingleton {
private static class InternalClassSingletonHandler {
public final static InternalClassSingleton instance = new InternalClassSingleton();
}
public static InternalClassSingleton getInstance() {
return InternalClassSingletonHandler.instance;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.