設計模式-建立型模式-單例模式

設計模式-建立型模式-單例模式es6

建立型模式

建立型模式隱藏類的實例和建立細節,經過隱藏對象如何建立組合在一塊兒達到整個系統獨立。web

單例模式

確保同一時刻只有一個實例被訪問。
Ensure a class has only one instance, and provide a global point of access to it. 確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例。數據庫

類圖

癡漢模式

在運行的時候直接加載實例化對象設計模式

package demo2;

// 演示單例模式
public class Singleton {
    // 在一加載的時候直接加載
    private final static Singleton singleton = new Singleton();
    // 確保不會被實例化
    private Singleton() {
        
    }
    // 其餘方法,建議使用static
    public static Singleton  getSingleton() {
        return singleton;
    }
}
package demo2;

public class Test {
    public static void main(String[] args) {
        Singleton.getSingleton();
    }
}

缺點

使用這個會形成在未使用的時候,出現大量的內存佔用。多線程

懶漢模式

即,在使用的時候實例化對象。ide

package demo2;

// 演示單例模式
public class Singleton {
    // 在一加載的時候直接加載
    private static Singleton singleton;
    // 確保不會被實例化
    private Singleton() {
        if (Singleton.singleton == null)
            Singleton.singleton = new Singleton();
    }
    // 其餘方法,建議使用static
    public static Singleton  getSingleton() {
        return singleton;
    }
}
package demo2;

public class Test {
    public static void main(String[] args) {
        Singleton.getSingleton();
    }
}

關於多線程

當在多線程的時候,因爲不是final,會形成出現多個實例化對象。使用同步鎖。工具

package demo2;

// 演示單例模式
public class Singleton {
    // 在一加載的時候直接加載
    private static Singleton singleton;
    // 確保不會被實例化
    private Singleton() {
        if (Singleton.singleton == null) {
            synchronized(this) {    // 同步
                // 若是此時已經有實例化對象,則不須要再次生成實例化對象
                if (Singleton.singleton == null) {
                    Singleton.singleton = new Singleton();
                }
            }
        }
    }
    // 其餘方法,建議使用static
    public static Singleton  getSingleton() {
        return singleton;
    }
}

應用

web頁面計數器,此時使用單例模式
訪問IO和數據庫資源的時候,使用單例模式
工具類,使用單例模式
數據庫的主鍵this

js單例模式

var Singleton = function(name){
    this.name = name;
}
// 添加方法
Singleton.prototype.getName = function(){
    return this.name;
}
// 構造
Singleton.getSingleton = function(name){
    if (!Singleton.instace){
        this.instace = new Singleton();
    }
    return this.instace;
}

es6單例模式

class Singleton{
    constructor(){
        this.name = "";
    }
    static getSingleton(){
        if(!this.instance){
            this.instance = new Singleton();
        }
        return this.instance;
    }
    getName(){
        return this.name;
    }
}

let a = Singleton.getSingleton();
let b = Singleton.getSingleton();
console.log(a === b);

實例

製做一個登錄彈窗的登陸界面
一個類,該類爲登陸框,構造方法裏,第一次點擊,構造出登陸對象,第二次點擊,不構造,使用的是單例模式,並設置幾個方法,爲顯示方法,關閉方法。最後綁定事件。spa

相關文章
相關標籤/搜索