单态设计模式
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一般Singleton模式通常有几种种形式:
第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。
one :
package test1;
public class Singleton {
public static Singleton instance = new Singleton() ;
private Singleton(){}
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static Singleton getInstance(){
return instance ;
}
public static void main(String[] args) {
Singleton S1 = new Singleton();
Singleton S2 = new Singleton();
System.out.println(Singleton.getInstance());
System.out.println(S1);
System.out.println(S2);
System.out.println(S2.toString()==S1.toString());
System.out.println(S2.equals(S1));
}
}
// Runtime、Class都采用了此类形式。
第二种形式:
two:
package test2;
public class Factory {
private static Factory factory = new Factory();
//这个方法比上面有所改进,只是第一次使用时生成实例,提高了效率
public static Factory getFactory() {
if (factory == null)
factory = new Factory();
// ...
return factory;
}
public static void main(String[] args) {
Factory S1 = new Factory();
Factory S2 = new Factory();
System.out.println(Factory.getFactory());
System.out.println(S1);
System.out.println(S2);
System.out.println(S2==S1);
System.out.println(S2.equals(S1));
}
}
一般认为第一种形式要更加安全些
three: Singletons and Threads
package test3;
public class Factory {
private static Factory factory;
private static Object classLock = Factory.class;
@SuppressWarnings("unused")
private long wipMoves;
private Factory() {
wipMoves = 0;
}
public static Factory getFactory() {
synchronized (classLock) {
if (factory == null)
factory = new Factory();
return factory;
}
}
public void recordWipMove() {
synchronized (classLock) {
wipMoves++;
}
}
public static void main(String[] args) {
Factory S1 = new Factory();
Factory S2 = new Factory();
System.out.println(Factory.getFactory());
System.out.println(S1);
System.out.println(S2);
System.out.println(S2 == S1);
System.out.println(S2.equals(S1));
}
}
典型应用
Hibernate框架中的 SessionFactory
package cn.edu.nynu.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sf;
static {
sf = new AnnotationConfiguration().configure().buildSessionFactory(); //使用Annotation生成SessionFactory的对象
// SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sf;
}
}