单例模式
定义:
确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例
使用场景:
实现单例模式几个关键点
例子:
public class Staff { public void work() { } }
public class VP extends Staff{ public void work() { } }
public class CEO extends Staff{ private static final CEO M_CEO = new CEO(); private CEO() { } public void work() { } public static CEO getCEO() { return M_CEO; } }
public class Company { private List<Staff> list = new ArrayList<>(); public void addStaff(Staff per) { list.add(per); } public void showStaff() { for(Staff staff : list) { System.out.println(staff.toString()); } } public static void main(String [] args) { Company company = new Company(); Staff ceo1 = CEO.getCEO(); Staff ceo2 = CEO.getCEO(); company.addStaff(ceo1); company.addStaff(ceo2); Staff vp1 = new VP(); Staff vp2 = new VP(); Staff staff1 = new Staff(); Staff staff2 = new Staff(); Staff staff3 = new Staff(); company.addStaff(vp1); company.addStaff(vp2); company.addStaff(staff1); company.addStaff(staff2); company.addStaff(staff3); company.showStaff(); } }
上面的例子就是饿汉模式,以下简单例子:
class Singleton{ private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
单例模式的其他实现方法
1、懒汉模式,线程安全
class Singleton{ private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
2、懒汉模式,线程不安全
上面的那个例子把 getInstance()方法的关键字synchronized去掉就是了
3、双重校验锁double check lock DCL
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
4、静态内部类单例模式
class Singleton{ private Singleton() { } public static Singleton getInstance() { return SingletonHolder.SINGLETON; } private static class SingletonHolder{ private static final Singleton SINGLETON = new Singleton(); } }
5、枚举单例模式
public enum Singleton { INSTANCE; public void whateverMethod() { } }
6、使用容器实现单例模式
class Singleton{ private static Map<String, Object> objMap = new HashMap<>(); private Singleton() { } public static void registerService(String key,Object object) { if(!objMap.containsKey(key)) { objMap.put(key, object); } } public static Object getService(String key) { return objMap.get(key); } }