编程题: 写一个Singleton出来,最好带注释解释一下什么意思,谢谢各位大大

解决方案 »

  1.   

    写一个单例出来,就是写一个类,构造方法是私有的,不能该类外部new ,然后写一个静态方法,可以根据类型调用得到该类的唯一实例
      

  2.   


    try{
    ServerPort port=new ServerPort(9000);}
    catch(IOException e){
    }原理很简单,检查是否端口已经被占用。不过你也可以使用文件锁来实现。就是项目下建立一个空文件,在程序启动时获取该文件的锁
    获取到则说明没有实例在运行,否则说明已经有实例运行不知道答案是不是你要的。
      

  3.   


    try { 
       ServerSocket   server   =   new   ServerSocket(9000); 
      } catch (IOException e) { 
       // TODO 自动生成 catch 块 
       System.out.println("端口被占用!"); 
      } 上述代码写错了,不好意思,呵呵
      

  4.   

    作用是一个类Class只有一个实例存在public class Singleton {
        private Singleton(){}
           // private只供内部调用 
           private static Singleton instance = new Singleton();
           //供外部访问本 class 的静态方法,可以直接访问   
           public static Singleton getInstance() {
             return instance;     
           } 
        } 
    }
      

  5.   

    单子模式singleton:
    //类属性,类方法
    private static SingleTonPattern stp;
    //注意返回的是对象
    public static SingleTonPattern getIntance(){          
    if(stp == null){
    stp = new SingleTonPattern();
    }
    return stp;
    在单子模式中只存在一个实例。很节约内存的。
      

  6.   


    public class SingleClass{
    private static SingleClass instance; 
    protected SingleClass(){}     public static SingleClass GetInstance() {
         if(instance == null)
                 {
                     instance = new SingleClass();
                 }
                 return instance;
             } }
      

  7.   


    //饿汉式
    public class EagerSingleton 

    //一上来就创建实例,所以叫饿汉
    private static final EagerSingleton m_instance = 
    new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() 
    {
      return m_instance; 
    }
    } //懒汉式
    public class LazySingleton 

      private static LazySingleton 
      m_instance = null;   private LazySingleton() { } 
     
      synchronized public static LazySingleton getInstance(){ 
      //实例为空的时候才创建,否者直接拿来用,所以是懒汉
      if (m_instance == null) 
      {
        m_instance = new LazySingleton(); 
      } 
      return m_instance; 
      }
      

  8.   

    //饿汉式
    public class EagerSingleton 

    //一上来就创建实例,所以叫饿汉
    private static final EagerSingleton m_instance = 
    new EagerSingleton(); 
    //private保证不能再被实例
    private EagerSingleton() { } public static EagerSingleton getInstance() 
    {
      return m_instance; 
    }
    } //懒汉式
    public class LazySingleton 

      private static LazySingleton 
      m_instance = null; 
      //private保证不能再被实例
      private LazySingleton() { } 
     
      synchronized public static LazySingleton getInstance(){ 
      //实例为空的时候才创建,否者直接拿来用,所以是懒汉
      if (m_instance == null) 
      {
        m_instance = new LazySingleton(); 
      } 
      return m_instance; 
      }

    构造方法是 private是单例模式关键
      

  9.   

    JAVA设计模式,普遍的单例有3种...