java singleton (单例模式)

public class TestSingleton {
 public static void main(String[] args) {
  MyClass c1=MyClass.newInstance();
  MyClass c2=MyClass.newInstance();
  System.out.println(c1==c2);
 }
}
//饿汉式
class MyClass{
 private static 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(){}
}
 

你可能感兴趣的:(java,Singleton,职场,休闲,(单例模式))