1:類加載時(shí)進(jìn)行對(duì)象的實(shí)例化:
public class SingletonA {
//SingletonA的唯一實(shí)例
private static SingletonA instance = new SingletonA();
//將構(gòu)造函數(shù)私有,防止外界構(gòu)造SingletonA實(shí)例
private SingletonA() {
}
/**
* 獲取SingletonA的實(shí)例
*/
public static SingletonA getInstance() {
return instance;
}
}
2:第一次訪問時(shí)進(jìn)行對(duì)象的實(shí)例化
public class SingletonB {
//SingletonB的唯一實(shí)例
private static SingletonB instance = null;
//將構(gòu)造函數(shù)私有遮婶,防止外界構(gòu)造SingletonB實(shí)例
private SingletonB() {
}
//獲取SingletonB的唯一實(shí)例椿争,用synchronized關(guān)鍵字保證某一時(shí)刻只有一個(gè)線程調(diào)用此方法碟绑。
public static synchronized SingletonB getInstance() {
//如果instance為空,便創(chuàng)建一個(gè)新的SingletonB實(shí)例颅眶,否則,返回已有的實(shí)例
if (instance == null) {
instance = new SingletonB();
}
return instance;
}
}