单例模式
只能创建唯一的对象:
- 饿汉模式(以空间换时间,类所含的资源较多时适用)
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; } }