栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式之单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式之单例模式

单例模式

特点:一个对象在JVM中有且仅有一个对象实例。同时构造器全部私有化。

(1)饿汉式
(2)懒汉式 【线程不安全】
(3)双锁单例

饿汉式

public class Singleton {
    
    private static Singleton singleton  = new Singleton();
    
    private Singleton() {}
    
    public static final Singleton getInstance() {
        return singleton;
    }
    
}

懒汉式

public class Singleton {

    private static Singleton singleton = null;

    private Singleton() {}

    public static final Singleton getInstance() {
        if (singleton == null) { // 线程安全
            singleton = new Singleton();
        }
        return singleton;
    }
}

但是这样会有一个问题,就是说在多线程的情况下,是会出现线程不安全的,所以我们可以稍稍改造一下。

懒汉式(线程安全)

public class Singleton {

    private static Singleton singleton = null;

    private Singleton() {}

	//当然这里的synchronized 关键字也可以加在方法上
    public static final Singleton getInstance() {
        synchronized(Singleton.class) {
            if (singleton == null) {
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}

双锁懒汉式

public class Singleton {

    private static volatile Singleton singleton = null;

    private Singleton() {}

	//当然这里的synchronized 关键字也可以加在方法上
    public static final Singleton getInstance() {
        synchronized(Singleton.class) {
            if (singleton == null) {
                singleton = new Singleton();
            }
        }
        return singleton;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970871.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号