用什么方法可以保证一个类只可以new一回请说具体点!谢谢 

解决方案 »

  1.   

    设计模式中的单例模式,不是可以new一回,是一直返回同一个对象
      

  2.   

    还是那句话,用单例模式
    单例模式的要点有三个;一是某各类只能有一个实例;二是它必须自行创建这个事例;三是它必须自行向整个系统提供这个实例。 
    单例模式有以下的特点: 1 单例类只可有一个实例。 2 单例类必须自己创建自己这惟一的实例。 3 单例类必须给所有其他对象提供这一实例。 public class EagerSingleton 

    private static final EagerSingleton m_instance = 
    new EagerSingleton(); 
    /** 
    * 私有的默认构造子 
    */ 
    private EagerSingleton() { } 
    /** 
    * 静态工厂方法 
    */ 
    public static EagerSingleton getInstance() 

    return m_instance; 

    } 在这个类被加载时,静态变量m_instance 会被初始化,此时类的私有构造子会被调用。这时候,单例类的惟一实例就被创建出来了。 
      

  3.   

    <pre name="code" class="java">
    public class ClassicSingleton { 
       private static ClassicSingleton instance = null; 
      
       protected ClassicSingleton() { 
          // Exists only to defeat instantiation. 
       } 
       public static ClassicSingleton getInstance() { 
          if(instance == null) { 
             instance = new ClassicSingleton(); 
          } 
          return instance; 
       } 

    </pre>
    http://www.javaeye.com/topic/60179
      

  4.   


    public class EagerSingleton  
    {  
    private static final EagerSingleton m_instance =  
    new EagerSingleton();  
    /**  
    * 私有的默认构造子  
    */  
    private EagerSingleton() { }  
    /**  
    * 静态工厂方法  
    */  
    public static EagerSingleton getInstance()  
    {  
    return m_instance;  
    }  
    }