1 单例模式要点
1.1 单例类只能有一个实例。
1.2 单例类必须自行创建唯一的实例
1.3 单例类必须向其它所有对象提供这一实例
2 单例类的实现方式:
2.1 饿汉式单例类:
class Singleton {
//私有,静态的类自身实例
private static Singleton instance = new Singleton();
//私有的构造子(构造器,构造函数,构造方法)
private Singleton(){}
//公开,静态的工厂方法
public static Singleton getInstance() {
return instance;
}
}
特点:在类加载的时候就创建了实例,且构造函数是私有的,实现了外界利用构造函数创造出多个实例,但是同时也由于构造函数私有是该类不能继承。
2.2 懒汉式单例类:
class LazySingleton {
//初始为null,暂不实例化
private static LazySingleton instance = null;
//私有的构造子(构造器,构造函数,构造方法)
private LazySingleton(){}
//公开,静态的工厂方法,需要使用时才去创建该单体
public static LazySingleton getInstance() {
if( instance == null ) {
instance = new LazySingleton();
}
return instance;
}
}
特点:在类第一次被引用的时候创建,且构造函数私有,使该类不能继承。
2.3 登记式单例类:
package pattern.singleton;
import java.util.HashMap;
import java.util.Map;
//登记式单例类.
//类似Spring里面的方法,将类名注册,下次从里面直接获取。
public class Singleton3 {
private static Map<String,Singleton3> map = new HashMap<String,Singleton3>();
static{
Singleton3 single = new Singleton3();
map.put(single.getClass().getName(), single);
}
//保护的默认构造函数
protected Singleton3(){}
//静态工厂方法,返还此类惟一的实例
public static Singleton3 getInstance(String name) {
if(name == null) {
name = Singleton3.class.getName();
System.out.println("name == null"+"--->name="+name);
}
if(map.get(name) == null) {
try {
map.put(name, (Singleton3) Class.forName(name).newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return map.get(name);
}
}
public class Singleton extends Singleton3 {
//默认构造函数
public Singleton(){}
public static Singleton getInstance(String name) {
return (Singleton) Singleton3 . getInstance(this.name())
}
}
特点:实现了类的继承;其子类必须在父类的帮助下才能实现实例化。由于子类和父类的数据类型不同,所以无法在父类中提供统一的方法;由于子类的构造函数是公开的,这样就允许产生的实例不再父类等集中了。
3 注意事项:
在多个JVM或者多个类加载器中应该注意单例模式的使用。因为多个类加载之间是绝缘的,多个JVM也是这样的
4 多例模式:
4.1 特点:多例类可有多个实例
4.2 必须自己创建、管理自己的实例,并且向外界提供自己的实例
本文详细介绍了单例模式的三大要点及其实现方式,包括饿汉式、懒汉式和登记式单例类,并探讨了多例模式的特点。
140

被折叠的 条评论
为什么被折叠?



