设计模式之单例模型
1.什么是单例模型
2.懒汉模式
/**
* 单例模型-懒汉模式
*
* @author Administrator
*
*/
public class Singleton {
private static Singleton instance = null; // instance 一开始没有引用任何对象
private final static ReentrantLock lock = new ReentrantLock();
private Singleton() {
}
/**
* 调用getIntance()方法,才建立instance的引用对象
*
* @return
*/
public static Singleton getIntance() {
lock.lock();
try {
if (instance == null) {
instance = new Singleton();
}
} finally {
lock.unlock();
}
return instance;
}
}
3.饿汉模式
/**
* 单例:饿汉模式
* @author Administrator
*
*/
public class Singleton2 {
private final static Singleton2 instance
= new Singleton2();//JVM保证线程安全
private Singleton2() {}
public static Singleton2 getIntance() {
return instance;
}
}