您的位置:首页 > 编程语言 > Java开发

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

2017-08-15 22:20 429 查看
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;
}


双重检查锁定背后的理论是完美的。不幸地是,现实完全不同。双重检查锁定的问题是:并不能保证它会在单处理器或多处理器计算机上顺利运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 设计模式