什么是单例模式
所谓的单例模式,指的是采用一定的手段来保证整个系统中对于某一个类只能存在一个实例对象,并且该类只提供了一个获取其实例对象的方法。
单例模式的设计思路
如果我们要让类只产生一个对象,那么我们就不能让外部调用其构造方法,首先必须将类的构造器的权限访问符设置为private,但是在类内部仍然可以产生该类的实例对象。
因为在外部无法无法获取到该类的实例对象,所以我们可以调用该类的某个静态方法来返回类内部创建的对象,静态方法只能访问类中的静态成员变量,所以,该类的对象成员也必须是静态的。
单例模式的分类和具体实现
单例模式有两种具体的实现方式:一种是饿汉式、另一种是懒汉式。我们必须手写来熟悉这样两种模式
饿汉式:一上来就创建成员对象
public class SingletonE {
// 饿汉式单例模式
private static SingletonE instance = new SingletonE();
private SingletonE() {
}
public static SingletonE getESingleton() {
return instance;
}
}
懒汉式
public class SingletonL {
private static SingletonL instance = null;
private SingletonL() {
}
public static SingletonL getLSingleton() {
if (instance == null) {
synchronized (SingletonL.class) {
if (instance == null) {
instance = new SingletonL();
}
}
}
return instance;
}
}