0
点赞
收藏
分享

微信扫一扫

笔试Java实现单例设计模式(最优方案)

public class SingletonTest  
{
private SingletonTest() //构造函数私有化
{
}

private static class Inner //私有的静态内部类
{
static SingletonTest singletonTest = new SingletonTest();
}

public static SingletonTest getInstance()
{
return Inner.singletonTest;
}
}

因为静态内部类只有在使用的时候才会被Classloader 加载。而JVM 类加载的时候又是线程安全的。


其他实现方法:

最常见(懒汉式)【线程不安全】:

public class SingletonTest  
{
private static SingletonTest singletonTest = null;

private SingletonTest()
{
}

public static SingletonTest getInstance()
{
//在类的静态方法中实例化单例
if (null == singletonTest)
{
singletonTest = new SingletonTest();
}

return singletonTest;
}
}

饿汉式

public class SingletonTest  
{
//在类里面实例化静态成员变量
private static SingletonTest singletonTest = new SingletonTest();

private SingletonTest()
{
}

public static SingletonTest getInstance()
{
return singletonTest;
}
}

双重检查锁

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}

双重检查锁定背后的理论是完美的。不幸地是,现实完全不同。双重检查锁定的问题是:并不能保证它会在单处理器或多处理器计算机上顺利运行。


举报

相关推荐

0 条评论