【设计模式】对单例模式的理解

AS WE KNOW ,单例模式是最基础的设计模式,在设计模式方面,单例模式有很多作用,另外在框架里面,ioc里面的bean默认就是单例。实际编程应用场景中,有一些对象其实我们只需要一个,比如线程池对象、缓存、系统全局配置对象等。这样可以就保证一个在全局使用的类不被频繁地创建与销毁,节省系统资源。

懒汉式

package pri.niddles.model;
//单线程还行  多线程不行
public class Lazy {

    private Lazy(){
    }

    private  static Lazy l ;

    public static Lazy getInstance(){
        if (l==null){
         l = new Lazy();
        }else {
            System.out.println("不能重复new 对象");
        }
        return l;
    }

}
package pri.niddles.model;
//版本2   加个锁
public class Lazy2 {

    private Lazy2(){
    }

    private  static Lazy2 l ;

    public static Lazy2 getInstance(){
        if (l==null){
            synchronized (Lazy2.class){
                if (l==null){

                    l = new Lazy2();
                }else {
                    System.out.println("不能重复new 对象");
                }
            }
        }
        return l;
    }

}

饿汉式

package pri.niddles.model;



//花样取对象  哈哈哈
//单例分为饿汉 懒汉  直接给和判断的区别

public class Hungry {


    //构造方法  也就是new这个对象的骨架

    //私有的最后不能更改的静态的(变成类的东西)
    private final static Hungry h = new Hungry();



    private Hungry() {
    }


    public static Hungry getInstance(){
        return h;
    }

    public static void main(String[] args) {

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

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

双重检测锁模式

public class Singleton {
	private volatile static Singleton singleton;
	private Singleton() {}
	public static Singleton getSingleton() {
		if (singleton == null) {
			synchronized (Singleton.class) {
				if (singleton == null) {
						singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
}

静态内部类

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值