微信搜索:小大白日志

单例模式

只能创建唯一的对象:
  • 饿汉模式(以空间换时间,类所含的资源较多时适用)
public class A{
      private static A a=new A();//我很饿了,先创建一个对象
    public static A getInstance(){
     return a;
  }
}

 

  • 饱汉模式(以时间换空间)
public class A{
  private static A a;//我很饱,先不创建对象
  public static synchronized A getInstance(){
  if(a==null) a=new A();
  return a;
 }
}
posted @ 2019-06-20 00:45  明天喝可乐  阅读(109)  评论(0)    收藏  举报