1. 单例模式的两种实现方式:
a) 饿汉式
b) 懒汉式(需要注意同步)
2. 了解单例模式的三要素
a) 私有的静态的成员变量
b) 私有的构造方法
c) 公共的静态的入口点方法
3. 单例模式的要点有三个
a) 一是某个类只能有一个实例;
b) 二是它必须自行创建这个实例;
c) 三是它必须自行向整个系统提供这个实例。
4. 单例模式的应用场景:类中没有可以修改的成员变量(这个类没有状态),如果存在可以修改的成员变量,将会产生线程安全问题,不建议使用。一些资源管理器(或管理类)常常设计成单例模式。
a) 饿汉式
public class ClientManager {
private static ClientManager instance = new ClientManager();
private ClientManager () {
}
public static ClientManager getInstance() {
return instance;
}
}
b) 懒汉式(需要注意同步)
public class UserManager {
private static UserManager instance = null;
private UserManager() {
}
public static synchronized UserManager getInstance() {
if(instance == null) {
instance = new UserManager();
}
return instance;
}
}
2. 了解单例模式的三要素
a) 私有的静态的成员变量
b) 私有的构造方法
c) 公共的静态的入口点方法
3. 单例模式的要点有三个
a) 一是某个类只能有一个实例;
b) 二是它必须自行创建这个实例;
c) 三是它必须自行向整个系统提供这个实例。
4. 单例模式的应用场景:类中没有可以修改的成员变量(这个类没有状态),如果存在可以修改的成员变量,将会产生线程安全问题,不建议使用。一些资源管理器(或管理类)常常设计成单例模式。