单例模式详解

一、概念

     1. java中单例模式是一种常见的设计模式,单例模式分三种:懒汉式单例、饿汉式单例、双重锁单例三种。


二、单例模式的特点:

          ① 单例类只能有一个实例。

          ② 单例类必须自己创建自己的唯一实例

          ③ 单例类必须给所有其他对象提供这一实例


三、单例代码

懒汉模式:

<span style="font-size:18px;">package com.test;

public class Singleton {
	public static Singleton instance = null;
	public static synchronized Singleton Instance(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}

	private Singleton(){
	};
	
}
</span>


饿汉模式

<span style="font-size:18px;">public class Singleton{
    //在自己内部定义自己的一个实例,只供内部调用
    private static final Singleton instance = new Singleton();
    private Singleton(){
        //do something
    }
    //这里提供了一个供外部访问本class的静态方法,可以直接访问
    public static Singleton getInstance(){
        return instance;
    }
}</span>


双重锁

<span style="font-size:18px;">public class Singleton{
    private static Singleton instance=null;
    private Singleton(){
        //do something
    }
    public static Singleton getInstance(){
        if(instance==null){
            synchronized(Singleton.class){
                if(instance==null)
{
                    instance=new Singleton();
                }
            }
        }
        return instance;
    }
}
 <code class="c# comments">//这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。</code></span>


 

                        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值