静态单线程函数.txt

来自「JAVA的静态单线程函数」· 文本 代码 · 共 27 行

TXT
27
字号
//单线程函数(保证每个类只生成一个实例)

class Singleton {
        private static Singleton s; 
        private Singleton(){};
        /**
             * Class method to access the singleton instance of the class.
         */
        public static Singleton getInstance() {
         if (s == null)
            s = new Singleton();
          return s;
        }
}

// 测试类
class singletonTest {
  public static void main(String[] args) {
    Singleton s1 = Singleton.getInstance();
    Singleton s2 = Singleton.getInstance();
    if (s1==s2)
      System.out.println("s1 is the same instance with s2");
    else
      System.out.println("s1 is not the same instance with s2");
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?