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

深入学习单例设计模式

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

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;
    }

}


未完待续...



上一篇:TortoiseSVN安装步骤图解与安装界面


下一篇:javaweb开发的路径问题