单例模式:
有一些对象我们只希望有一个,例如线程池、缓存、日志对象等。这个时候就可以用到单利模式,单例可以确保一个类只有一个实例,并且提供一个全局访问点。
常见的单例:
1. 经典的单例:
/** * Created on 2016/11/15. * 经典单利模式 */ public class Person1 { private static Person1 person1; private Person1(){} public static Person1 getInstance(){ if(person1 == null){ person1 = new Person1(); } return person1; } }2. 解决多线程问题的单例:
/** * Created on 2016/11/15. * 多线程单利模式 */ public class Person2 { private static Person2 person2; private Person2(){} //缺点:同步方法会大大降低程序的执行效率 public static synchronized Person2 getInstance(){ if(person2 == null){ person2 = new Person2(); } return person2; } }3. 急切用到,并且使用频繁使用到这个对象的实例:
/** * Created on 2016/11/15. * "急切"创建实例 */ public class Person3 { //适用于频繁创建使用单利的情况 private static Person3 person3 = new Person3(); private Person3(){} public static Person3 getInstance(){ return person3; } }4. 双重验证:
/** * Created on 2016/11/15. * "双重"创建模式:推荐这种方式(java1.4以上) */ public class Person4 { /** * volatitle关键字:当person4被实例化之后,多线程能正确的使用处理person4 * 不适用于1.4及更早的java中 */ private volatile static Person4 person4; private Person4(){} /** * 如果没有创建才同步,这样只有第一次创建才进行同步 */ public static Person4 getInstance(){ if(person4 == null){ synchronized (Person4.class){ if(person4 == null){ person4 = new Person4(); } } } return person4; } }