单例模式之饿汉模式实现
不要问为什么,问就是爱过,上代码:
package singleton;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
*
* @ClassName: HungrySingleton
* @Description:TODO(这里用一句话描述这个类的作用)
* @author: 长子科技
* @date: 2021年7月7日 下午9:07:35
*
* @Copyright: 2021 www.tydic.com Inc. All rights reserved.
* 注意:本内容仅限于长子科技股份有限公司内部传阅,禁止外泄以及用于其他的商业目
*/
public class HungrySingleton implements Cloneable,Serializable{
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = 1L;
private volatile static HungrySingleton instance=new HungrySingleton();
//避免反射产生新的单例
private HungrySingleton(){
if(instance!=null){
throw new RuntimeException("单例已经实例化了,不能再实例化对象了");
}
}
public static HungrySingleton getInstance() {
return instance;
}
//避免克隆产生多个实例。
@Override
public HungrySingleton clone(){
return instance;
}
//避免反序列化导致产生多个实例
private Object readResolve(){
return instance;
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException, ClassNotFoundException, CloneNotSupportedException {
HungrySingleton instance1=HungrySingleton.getInstance();
System.out.println("instance1:"+instance1.hashCode());
//通过反序列话获取单例
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(instance1);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois=new ObjectInputStream(bis);
HungrySingleton instance3=(HungrySingleton)ois.readObject();
System.out.println("instance3:"+instance3.hashCode());
//通过克隆获取对象
HungrySingleton instance4=(HungrySingleton) instance1.clone();
System.out.println("instance4:"+instance4.hashCode());
//反射方式获取对象
Constructor<HungrySingleton> declaredconstructor=HungrySingleton.class.getDeclaredConstructor();
declaredconstructor.setAccessible(true);
HungrySingleton instance2=declaredconstructor.newInstance();
System.out.println("instance2:"+instance2.hashCode());
}
}
结果:
instance1:366712642
instance3:366712642
instance4:366712642
Exception in thread “main” java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at singleton.HungrySingleton.main(HungrySingleton.java:69)
Caused by: java.lang.RuntimeException: 单例已经实例化了,不能再实例化对象了
at singleton.HungrySingleton.(HungrySingleton.java:32)
… 5 more
经过上一节(单例模式之懒汉模式实现)的演示,本章直接上最终代码,给大家,看一个安全的饿汉单例模式的实现。