首页 > 代码库 > 单例模式

单例模式

public class TestSingleton{

  public static void main(String[] args){

  MyClass mc = MyClass.newInstance();

  }

}

class MyClass {

  private static final MyClass instance = new MyClass();

  public static MyClass newInstance(){

  return instance;

  }

  private MyClass(){}

}

 

class MyClass2{

  private static MyClass2 instance = null;

  public static synchronized Myclass2 newInstance(){

    if (instance == null) instance = new MyClass2();

    return instance;

  }

  private MyClass2(){}

}

单例模式