概念
一種創(chuàng)建型模式,確保系統(tǒng)中一個(gè)類(lèi)只產(chǎn)生一個(gè)實(shí)例
好處
1 頻繁使用的對(duì)象抄肖,可以省略創(chuàng)建對(duì)象所花的時(shí)間
2 New操作次數(shù)減少,因?yàn)橄到y(tǒng)內(nèi)存的使用頻率也會(huì)降低(減輕GC壓力和GC停頓時(shí)間)
例子
public class Singleton{
private Singleton(){
System.out.println("create singleton");
if (SingleHolder.singleton != null){
throw new IllegalStateException();
}
}
private static class SingleHolder{
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return SingleHolder.singleton;
}
}