确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
有的类在使用的时候不管在什么地方都需要能取到,它的一些属性需要在不同共享,又不便于多次创建,这样的情况,我们就应该使用单例模式。
立即加载的单例模式
class Test2{ //私有的构造方法 private Test2(){} //私有创建该对象 private static Test2 test = new Test2(); //公有的方法,被外部调用获取对象 public static Test2 getTest(){ return test; } }懒加载的单例模式
class Test { //懒加载的单例模式 private Test(){} //在这里对象为null private static Test test = null; //当被调用该方法时,先判断该对象是否被实例,实例直接返回,否则先实例在返回 public static Test getTest(){ if (test == null){ test = new Test(); } return test; } }但是可能会遇到多线程的问题于是我们给get方法加同步或者加锁
public static synchronized Test getTest(){ if (test == null){ test = new Test(); } return test; } public static Test getTest(){ if (test == null){ synchronized (Test.class) { if (test == null) { test = new Test(); } } } return test; }