자바 단일 모드 생 성 방식
10329 단어 디자인 모드
굶 주 린 남자 모델
package com.test.module.entity;
/**
*
* @author admin_an
*
*/
public class Singleton {
/**
* : , 。
* , ,
* , ,
* 。 ,
*/
private static Singleton single = new Singleton();
private Singleton() {
// TODO Auto-generated constructor stub
}
public static Singleton getInstance() {
return single;
}
} 게으름뱅이 모드
/**
* : , ,
* , 。
* ,
*
* : , getInstance() ,
* ,
*/
private static Singleton single = null;
private Singleton() {
}
public static Singleton getInstance() {
if(single == null) {
single = new Singleton();
}
return single;
} /**
* :
* ,
*
* : ,synchronized ,
* getInstance(), synchronized ,
*/
private static Singleton single = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(single == null) {
single = new Singleton();
}
return single;
} /**
* : instance 。
* , getInstance() ,
* , , getInstance() ,
*
*
* : A、B,A if (instance == null) , ,
* B ,B , ,
* 。
*/
private static Singleton single = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(single == null) {
synchronized (Singleton.class) {
single = new Singleton();
}
}
return single;
} 이중 검사 잠 금 모드
/**
* getInstance() , null 。 , ,
* , , ,
*
*
* :Java , , 。
* JVM , JVM 。
* , ,
* 。
* , , 。
* , , 。
* single , ,
* getInstance(), , 。
*/
private static Singleton single = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(single == null) {
synchronized (Singleton.class) {
if(single == null) {
single = new Singleton();
}
}
}
return single;
} /**
* JDK1.5 volatile 。volatile ,
* single , 。
*
* jdk1.5 。
* JDK volatile 。
* , jdk1.5 ,
*/
private static volatile Singleton single = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if(single == null) {
synchronized (Singleton.class) {
if(single == null) {
single = new Singleton();
}
}
}
return single;
} 정적 내부 클래스 모드
public class Singleton {
/**
* :
* Singleton , Singleton ,
* ,
*
* single 。 , ,
* 。
* , , , ,
* JVM , , 。
*
*/
private static class SingletonHolder {
public static Singleton single = new Singleton();
}
private Singleton() {
}
public static synchronized Singleton getInstance() {
return SingletonHolder.single;
}
} 위 에서 언급 한 네 가지 단일 사례 를 실현 하 는 방식 은 모두 공 통 된 단점 이 있다. 1) 추가 적 인 작업 으로 직렬 화 를 실현 해 야 한다. 그렇지 않 으 면 매번 직렬 화 된 대상 을 반 직렬 화 할 때마다 새로운 인 스 턴 스 를 만들어 야 한다.2) 반사 로 개인 구조 기 를 강제로 호출 할 수 있 습 니 다 (이 를 피 하려 면 구조 기 를 수정 하여 두 번 째 인 스 턴 스 를 만 들 때 이상 을 던 질 수 있 습 니 다).
매 거 법
/**
*
* , ,
* ,
*
* enum class ,enum Enum ,
* enum , 。
* ,enum , , final 。
* enum private , , ,
*
*
* Enum Java 。
* public static final T ,
* , 。
* , , ,
* (lazy-loading) 。
*
* , JVM ,
* Java ,
* writeObject、readObject、readObjectNoData、writeReplace readResolve
* , readObject 。
*
* , , 。
*/
public enum SingletonDemo {
SINGLE;
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name= name;
}
public void whateverMethod(){ }
}