单例模式的要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。大多数的软件都有一个(甚至多个)属性文件存放系统配置。这样的系统应当由一个对象来管理一个属性文件。
单例模式的结构:
1.饿汉单例模式
package com.test03;
public class EagerSingleton {
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return m_instance;
}
}
在这个类被加载时,静态变量m_instance会被初始化,此时类的私有构造器会被调用。这时候,单例类的唯一实例就被创建出来了。java语言中单例类的一个最重要的特点是类的构造器是私有的,从而避免外界利用构造器直接创建出任意多的实例。
2.懒汉式单例类
package com.test03;
public class LazySingleton {
private static LazySingleton m_instance = null;
private LazySingleton() {
super();
}
public static synchronized LazySingleton getInstance() {
if(m_instance ==null ) {
m_instance = new LazySingleton();
}
return m_instance;
}
}