几个单例模式

package com.bsoft.test;

public class Silgton {
	 public static void main(String[] args) throws Exception{   
	        System.out.println(单例1.单例调用());   
	        System.out.println(单例1.单例调用());   
	        System.out.println(单例1.单例调用());
	        System.out.println(单例2.单例调用());
	        System.out.println(S3.class);
	        System.out.println(S4.getInstance());
	    }   
}

/**
 * 优点:  
1.线程安全的
2.在类加载的同时已经创建好一个静态对象,调用时反应速度快。
缺点: 
资源利用效率不高,可能getInstance永远不会执行到,但是执行了该类的其他静态方法或者加载了该类(class.forName),那么这个实例仍然初始化了
 * 预先加载单例
 * @author qyb
 *饿汉单例
 */
class 单例1{
	private 单例1(){
		System.out.println("单例1");
	}
	private static 单例1 单例对象1 = new 单例1();
	
	public static 单例1 单例调用(){
		return 单例对象1;
	}
}

/**
 * 优点: 资源利用率高,不执行getInstance就不会被实例,可以执行该类其他静态方法。
缺点: 第一次加载时发应不快  ,多线程使用不必要的同步开销大
 * 延迟加载单例
 * 考虑多线程方面
 * @author qyb
 *懒汉单例
 */
class 单例2{
	private 单例2(){
		System.out.println("单例2");
	}
	
	private static 单例2 单例对象2 = null;
	
	public static synchronized 单例2 单例调用(){
		if(单例对象2 == null){
			单例对象2 = new 单例2();
		}
			return 单例对象2;
	}
}

/**
 * 优点: 资源利用率高, 不执行getInstance就不会被实例,可以执行该类其他静态方法。
缺点: 第一次加载时发应不快  ,由于java 内存模型一些原因偶尔会失败
 * 双重检测( 考虑多线程 )
 * @author qyb
 *
 */
class S3{
	private S3(){
		System.out.println("S3");
	}
	
	private static S3 instance = null;
	
	public static synchronized  S3 getInstance(){
		if(instance == null){
			synchronized (S3.class){
				if(instance == null){
					instance = new S3();
				}
			}
		}
		return instance;
	}
}

/**
 * 优点: 资源利用率高, 不执行getInstance就不会被实例,可以执行该类其他静态方法。
缺点: 第一次加载时发应不快
 * @author qyb
 *
 */
class S4{
	private S4(){
		System.out.println("S4");
	}
	
	private static class S4Holder{
		static S4 instance = new S4();  
	}
	
	  public static S4 getInstance() {   
	    return S4Holder.instance;   
	}  
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值