單例模式
1.定義
????????單例也叫單態(tài)模式, 是設(shè)計(jì)模式中最簡(jiǎn)單的一種。當(dāng)一個(gè)類被創(chuàng)建之后, 只能產(chǎn)生一個(gè)實(shí)例供外部訪問, 并且提供一個(gè)全局訪問的方法。
? ? ? ? 單例的最終目的就是保證一個(gè)類在內(nèi)存中只能有一個(gè)實(shí)例(對(duì)象)。
? ? ? ? Java中頻繁創(chuàng)建和銷毀類對(duì)象都會(huì)占用一部風(fēng)系統(tǒng)資源,使用單例模式可以提高性能。
? ? ? ? 單例模式創(chuàng)建的對(duì)象不會(huì)被回收,過多的單例照成內(nèi)存溢出。
2.創(chuàng)建過程
? ? ? ? 私有化構(gòu)造方法(使用private修飾)
? ? ? ? 在其內(nèi)部產(chǎn)生該類的實(shí)例化對(duì)象,并將其封裝成private static 類型
? ? ? ? 定義一個(gè)靜態(tài)的方法返回該類的實(shí)例
3.餓漢式和懶漢式
餓漢式
public class Singleton{
? ? private static Singleton singleton = new Singleton();
? ? private Singleton(){}
? ? public static Singleton getInstance(){
????????return singleton;
????}
}
懶漢式
public class Singleton{
? ? private static Singleton singleton;
? ? private Singleton(){}
? ? public static Singleton getInstance(){
? ? if(singleton==null){
? ? ? ? singleton = new Singleton();
????????}
? ? ? ? return singleton;
????}
}