首页 > 其他 > 详细

单例模式

时间:2018-08-30 16:24:12      阅读:171      评论:0      收藏:0      [点我收藏+]

1、饿汉式单例模式

//饿汉式单例
public class Singleton
{
    private Singleton(){}
    private Singleton uniqueInstance = new Singleton();
    public static Singleton getInstance(){
        return uniqueInstance;
    }
}

2、懒汉式单例模式

//懒汉式单例,延迟实例化
public class Singleton
{
    private Singleton uniqueInstance;
    private Singleton(){}
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

3、双重加锁单例模式

//双重加锁,应对多线程
public class Singleton
{
    private volatile static Singelton uniqueInstance;
    private Singleton(){}
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            synchronized (Singleton.class){
                if(uniqueInstance==null){
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

 

单例模式

原文:https://www.cnblogs.com/xiaoxli/p/9560648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!