单例模式 定义:Singleton模式是 Java 中最简单的设计模式之一。这种类型的设计模式属于创造性模式,因为这种模式提供了创建对象的最佳方式之一。
该模式涉及一个类,该类负责创建一个对象,同时确保只创建一个对象。该类提供了一种访问其唯一对象的方法,可以直接访问该对象,而无需实例化该类的对象
public class static Singleton {
private StaticSingleton(){
System.out.println("StaticSingleton实例创建");
}
private static class SingletonHolder{
private static StaticSingleton instance = new Static Singleton();
}
public static StaticSingleton getInstance () {
return SingletonHolder.instance;
}
}
在上面的例子中使用内部类来维护单例的实例,当StaticSingleton被加载时,其内部类并不会被初始化,当getInstance()方法被调用时,才会加SingletonHolder,从而初始化instance。由于实例的建立是在类加载时完成,故天生 对 多线程 友好 ,getInstance()方法也不需要使用同步关键字,同时做到了 延迟加载 单例的模式。
注意:通过 反射机制 强行调用单例类的私有构造函数,生成多个实例,该极端情况不讨论。
一个可以被串行化的单例模式:
//单例定义
public class SerSingleton implements Serializable {
String name;
private SerSingleton() {
System.out.println("StaticSingleton实例创建");
name = "hello";
}
private static SerSingleton instance = new SerSingleton();
public static SerSingleton getInstance() {
return instance;
}
private Object readResolve() {
return instance;
}
}
//测试方法
@org. junit .Test
public void test() throws IO Exception , ClassNotFoundException {
SerSingleton instance = null;
SerSingleton instance2 = SerSingleton.getInstance();
FileOutputStream fos = new FileOutputStream("SerSingleton.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(instance2);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("SerSingleton.txt");
ObjectInputStream ois = new Object InputStream (fis);
instance = (SerSingleton) ois.readObject();
Assert.assertEquals(instance,instance2);
}
单例类实现readResolve()函数的测试结果
单例类未实现readResolve()函数的测试结果
序列化 和反序列化可能会破坏单例,遇到该情况需要多加注意,在单例类中实现readResolve()方法就可以任然保持单例的特点。在实现私有的readResolve()方法之后,readObject()方法会直接使用readResolve()替换原本的返回值,从而在形式上构造了单例。
总结单例设计模式优点:
1、对于频繁使用的对象,可以省略创建对象的时间,对于系统内的重量级对象而言,是非常可观的一笔系统开销
2、减少了new操作次数,减轻了GC压力,缩短GC停顿时间,从而提高了系统性能
星星之火可以燎原,加油吧,少年!!!