单例模式--饿汉式、懒汉式、线程安全的懒汉式、高性能安全的懒汉式

深入学习单例设计模式

饿汉式单例:开发时较为常用。

class Single1 {
	private Single1(){}
	private static Single1 single = new Single1();
	public static Single1 getInstance() {
 	      return single;
	}
	public static void main(String[] args) {
		Single1 s = Single1.getInstance();
		Single1 s1 = Single1.getInstance();
		System.out.println(s==s1);
	}
}




多线程会出现问题的懒汉式单例:

class Single2{
private Single2(){}
private static Single2 single = null;
public static Single2 getInstance(){
if (single == null) {
single = new Single2();
}
return single;
}
public static void main(String[] args) {
Single2 s = Single2.getInstance();
Single2 s1 = Single2.getInstance();
System.out.println(s==s1);
}
}

 解决多线程安全问题的懒汉式单例


class Single3{
private Single3(){}
private static Single3 single = null;
public static synchronizedSingle3 getInstance(){
if (single == null) {
single = new Single3();
}
return single;
}
public static void main(String[] args) {
Single3 s = Single3.getInstance();
Single3 s1 = Single3.getInstance();
System.out.println(s==s1);
}
}


懒汉式的目的是为了提高性能,synchronized却降低了性能


class Single4{
private Single4(){}
private static Single4 single = null;
public static Single4 getInstance(){
if (single == null) {
synchronized(Single4.class) {
if (single == null)
{
single = new Single4();
}
}
}
return single;
}
public static void main(String[] args) {
Single4 s = Single4.getInstance();
Single4.s1 = Single4.getInstance();
System.out.println(s==s1);
}
}

比较推荐的还是第一种饿汉式单例(Hibernate4中官方源码):

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            new Configuration().configure().buildSessionFactory(
			    new StandardServiceRegistryBuilder().build() );
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}


未完待续...



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值