单例模式
好处:1、对于频繁使用的对象可以省略创建对象所花费的时间;
2、由于new操作的减少,从而减少了对内存使用频率,
单例模式 的核心在与通过一个接口返回唯一的对象实例。如下是简单的创建单例:
public class Singleton{
private Singleton(){};
private static Singleton instance = new Singleton();
public static Singletion getInstance(){
return instance;
}
}
此种单例的实现方式简单,唯一的不足是无法为实例做延迟加。如果在单例类不仅仅用来创建单例实例,还用来进行创建String对象。
public class Singleton{
private Singleton(){
System.out.println("Sigleton is creating");
}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public static void createString(){
System.out.println("String is create in Singleton ");
}
}
在控制台中输出后,如果调用createString()时,会进行实例的创建,无法做到延迟加载。
延迟加载:
public class Singleton{
private Singleton(){
}
private static Singleton instance = null;
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
使用延迟加载的单例后,因为加了同步的代码,因此在多线程的情况下,花费的代价要大,即延迟加载的单例对于多线程不友好。
对于多线程友好的单例使用内部类来进行创建单例,
public class InnerSingleton {
private InnerSingleton(){
}
private static class InnerClass{
private static InnerSingleton instance = new InnerSingleton();
}
public static InnerSingleton getInstance(){
return InnerClass.instance;
}
}
当InnerSingleton类加载时,内部类不会进行加载,所以当InnerSingleton加载进入JVM时,不会初始化内部类,当调用getInstance()时才会加载InnerClass从而进行实例化。同时,实例的建立实在类加载的时候完成的,因此,对多线程优化。
通常情况下,使用内部类创建单例可以确保在系统中只存在唯一的实例了。但任然有例外情况,可能导致系统生成多个实例,比如在代码中,通过反射机制,强行调用单例类的私有构造函数,生成多个单例。通过序列化和反序列化后生成的对象可能不是单例模式。
package com.performance.optimization.design.singleton;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 可序列化的单例
* @author qiaolin
*
*/
public class SerSingleton implements Serializable{
private static final long serialVersionUID = 3641141275445251177L;
private SerSingleton(){
System.out.println("singleton is create ");
}
private static SerSingleton instance = new SerSingleton();
public static SerSingleton getInstance(){
return instance;
}
public static void createString(){
System.out.println("create string in SerSingleton ");
}
/**
* 阻止生成新的实例,返回当前的,确保唯一性
* 此方法会在调用readObject之后调用,如果有此方法则调用此方法返回对象,如果没有则返回readObject的对象
* @see java.io.ObjectStreamClass invokeReadResolve
* @return
*/
private Object readResolve(){
return instance;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
SerSingleton ser = null;
SerSingleton serOld = SerSingleton.getInstance();
//序列化到本地
FileOutputStream fos = new FileOutputStream("singleton");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serOld);
oos.flush();
oos.close();
//反序列化
FileInputStream fis = new FileInputStream("singleton");
@SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fis);
ser = (SerSingleton) ois.readObject();
ois.close();
System.out.println(ser == serOld);
}
}