日期:2014-05-17  浏览次数:20777 次

怎么实现一个类 无法禁止通过new来实例化?
怎么实现一个类  无法禁止通过new来实例化?

------解决方案--------------------
把构造函数私有化
public class clsClass
{
   private clsClass()
   {
   }
}
------解决方案--------------------
构造函数私有呗
------解决方案--------------------
非抽象类,非静态类,构造函数私有化
典型的就是单例模式,通过静态方法来获取实例
public class Singleton
{
        private static Singleton instance;

        private Singleton()
        {
        
        }

        public static Singleton GetInstance()
        {
                if(instance==null)
                {
                        instance=new Singleton();
                }
                return instance;
        }
}

------解决方案--------------------
私有构造函数 
------解决方案--------------------

public class testClass
{
    private testClass()
    {
    }
    private static object _obj = new object();
    private static testClass _instance = null;
    public static testClass Instance()
    {
        if (_instance == null)
        {
            lock (_obj)
            {
                if (_instance == null)
                {
                    _instance = new testClass();
                }
            }
        }
        return _instance;
    }
}