【java设计模式】(1)单例模式

package design;

/**
 * 单例模式:一个类只能对外部提供一个可访问实例
 * 1.类的构造器需要私有化(private修饰)
 * 2.产生的对象为private static类型
 * 3.定义一个静态方法返回该类的实例
 * 方法四为单例模式的最佳实现。内存占用地,效率高,线程安全,多线程操作原子性。
 * @author Solitude
 *
 */
public class Singleton {

	private Singleton(){		
	}
	
	private static final Singleton instance = new Singleton();
	private static Singleton instance2;
	private static Singleton instance3;
	//定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,
	//避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
	private static volatile Singleton instance4;
	
	/**
	 * 单例模式的实现:饿汉式,线程安全 但效率比较低 
	 * @return
	 */
	public static Singleton getSingleton(){
		return instance;
	}
	
	/**
	 * 单例模式的实现:饱汉式,非线程安全   
	 * @return
	 */
	public static Singleton getSingleton2() {
		if(instance2 == null){
			instance2 = new Singleton();
		}
		return instance2;
	}
	
	/**
	 * 单例模式的实现:饱汉式,线程安全简单实现   
	 * @return
	 */
	public static synchronized Singleton getSingleton3() {
		if(instance3 == null){
			instance3 = new Singleton();
		}
		return instance3;
	}
	
	/**
	 * 单例模式最优方案:线程安全  并且效率高 
	 * @return
	 */
	public static Singleton getSingleton4() {
		if(instance4 == null){
			synchronized (Singleton.class) {
				if(instance4 == null){
					instance4 = new Singleton();
				}
			}
		}
		return instance4;
	}
	
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值