笔试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;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值