单例模式
单体模式的不同变现形式:
1.饿汉单例模式
2.懒汉单例模式
3.多例模式
1.饿汉单例模式
略
2.懒汉单例
//双锁模式(线程安全,效率低下,适合初次启动加载一次的)
略
//内部类模式
/**
* 线程安全,效率高,并且实现延迟加载
*/
class lazy implements Serializable
{
private static class SingletonCalssInstance
{
private static final lazy instance = new lazy();
}
private lazy()
{
//做一些防止反射暴力创建
if ( SingletonCalssInstance.instance != null )
throw new RuntimeException("单例禁止");
}
public static lazy getInstance()
{
return SingletonCalssInstance.instance;
}
//防止反序列化获取多个对象
private Object readResolve() throws ObjectStreamException
{
return SingletonCalssInstance.instance;
}
}
3.多例模式----双例
public class Many {
private static Many many1 = new Many();
private static Many many2 = new Many();
private Many()
{
}
public static Many getInstance (int whickOne)
{
if (whickOne == 1)
return many1;
else
return many2;
}
}
来源:CSDN
作者:S_simple_
链接:https://blog.csdn.net/S_simple_/article/details/103125481