月眸


常见的三种单例模式

毛毛小妖 2019-10-08 610浏览 4条评论
首页/正文
分享到: / / / /

一、懒汉模式

package com.sy.singleton;

/**
 * 描述: 懒汉模式
 * @author shengyu 
 * @date:2019年5月7日 下午4:33:12
 */
public class SingletonExample1 {

	private SingletonExample1(){
		
	}
	
	private static SingletonExample1 instance = null;
	
	public SingletonExample1 getInstance(){
		if (instance == null) {
			instance = new SingletonExample1();
		}
		return instance;
	}
}

二、饿汉模式

package com.sy.singleton;

/**
 * 描述: 饿汉模式
 * @author shengyu 
 * @date:2019年5月7日 下午4:34:58
 */
public class SingletonExample2 {

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

三、懒汉模式,双重同步锁单例模式

package com.sy.singleton;

/**
 * 描述: 懒汉模式,双重同步锁单例模式
 * @author shengyu 
 * @date:2019年5月7日 下午3:59:15
 */
public class SingletonExample {
	private SingletonExample(){
		
	}
	
	private volatile static SingletonExample instance = null;
	
	public static SingletonExample getInstance(){
		if(instance == null){
			synchronized (SingletonExample.class) {
				if (instance == null) {
					instance = new SingletonExample();
				}
			}
		}
		return instance;
	}
}

 

最后修改:2019-10-08 16:17:51 © 著作权归作者所有
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

上一篇
登录即可评论哦~

评论列表

毛毛小妖 2019-10-16 16:46:55
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/25.gif" alt="[抱抱]">
jishubu 2019-10-16 12:30:23
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/0.gif" alt="[微笑]">
回复
毛毛小妖 2019-10-16 16:46:33
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/25.gif" alt="[抱抱]">
匿名用户 2019-10-16 12:30:43
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/1.gif" alt="[嘻嘻]">
回复
匿名用户 2019-10-16 12:30:43
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/1.gif" alt="[嘻嘻]">
回复
jishubu 2019-10-16 12:30:23
<img src="https://www.eyesmoons.com/templates/perfree-simple-pro/static/plugins/layui/images/face/0.gif" alt="[微笑]">
回复