参考:http://cantellow.iteye.com/blog/838473
什么是单例?
Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”通俗的说:对于某个类来说,在整个项目中仅希望存在一个实例。不管是谁调用,在哪里调用,调用的都是同一个实例。
单例的实现:
1. 构造器私有化 ------> 不能被随随便便 new 出来
2. 自己创造一个实例,并提供一个接口调用,可供其他调用者调用接口获得该实例
实现单例的几种方式:
1.
/** * 懒汉式 : 很形象,就像一个懒人一样,东西什么时候需要用到,才去加载 * 缺点:线程不安全 * */ public class Singleton001 { private static Singleton001 instance ; private Singleton001(){ } public static Singleton001 getInstance(){ if(instance==null){ instance = new Singleton001(); } return instance; } }
2.
/** * 懒汉式 线程安全 * * 加锁 * * 缺点:效率低 */ public class Singleton002 { private static Singleton002 instance; private Singleton002(){} public static synchronized Singleton002 getInstance(){ if ( instance == null ){ instance = new Singleton002(); } return instance; } }
3.
/** * 恶汉式 : 也很形象,像一个恶汉一样,饥渴难耐,迫不及待 * 一启动就加载,迫不及待 */ public class Singleton003 { private static Singleton003 instance = new Singleton003(); private Singleton003(){} public static Singleton003 getInstance(){ return instance; } }
4.
/** * 饿汉式 变种 */ public class Singleton004 { private static Singleton004 instance = null; static{ instance = new Singleton004(); } private Singleton004(){} public static Singleton004 getInstance(){ return instance; } }
5.
/** * 静态内部类 */ public class Singleton005 { private static class singletonHolder{ private static final Singleton005 INSTANCE = new Singleton005(); } private Singleton005(){} public static final Singleton005 getInstance(){ return singletonHolder.INSTANCE; } }
6.
/** * 枚举 */ public enum Singleton006 { INSTANCE; public void whatEverMethod(){ System.out.println(55555555); } }
这样子调用
Singleton006 s6 = Singleton006.INSTANCE; s6.whatEverMethod(); Singleton006 s7 = Singleton006.INSTANCE; s7.whatEverMethod(); System.out.println(s6==s7);
7.
/** * 双重校验锁 */ public class Singleton007 { private static Singleton007 instance; public static Singleton007 getInstance(){ if (instance == null){ synchronized(Singleton007.class){ if (instance == null){ instance = new Singleton007(); } } } return instance; } }