设计模式-创建型模式-单例模式

设计模式-创建型模式-单例模式

创建型模式

创建型模式隐藏类的实例和创建细节,通过隐藏对象如何创建组合在一起达到整个系统独立。

单例模式

确保同一时刻只有一个实例被访问。
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();
    }
}

缺点

使用这个会造成在未使用的时候,出现大量的内存占用。

懒汉模式

即,在使用的时候实例化对象。

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和数据库资源的时候,使用单例模式
工具类,使用单例模式
数据库的主键

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);

实例

制作一个登陆弹窗的登录界面
一个类,该类为登录框,构造方法里,第一次点击,构造出登录对象,第二次点击,不构造,使用的是单例模式,并设置几个方法,为显示方法,关闭方法。最后绑定事件。
www.iming.info

猜你喜欢

转载自www.cnblogs.com/melovemingming/p/10023904.html
今日推荐