两种实现单例模式的方式:
//饿汉式
public class EagerSingleton
{
//一上来就创建实例,所以叫饿汉
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance()
{
return m_instance;
}
}
//懒汉式
//懒汉式
public class LazySingleton
{
private static LazySingleton m_instance = null;
private LazySingleton() { }
synchronized public static LazySingleton getInstance(){
//实例为空的时候才创建,否者直接拿来用,所以是懒汉
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}