标签:
单例模式保证一个类中只有一个实例且该实例易于外界访问。
懒汉模式(第一次调用的时候实例化,懒加载)
public class SingletonClass{ private static SingletonClass instance=null; public static synchronized SingletonClass getInstance() { if(instance==null) { instance=new SingletonClass(); } return instance; } private SingletonClass(){ } }
饿汉模式(调用之前实例化)
public static class Singleton{ //在自己内部定义自己的一个实例,只供内部调用 private static final Singleton instance = new Singleton(); private Singleton(){ //do something } //这里提供了一个供外部访问本class的静态方法,可以直接访问 public static Singleton getInstance(){ return instance; } }
双重锁模式
public static class Singleton{ private static Singleton instance=null; private Singleton(){ //do something } public static Singleton getInstance(){ if(instance==null){ synchronized(Singleton.class){ if(null==instance){ instance=new Singleton(); } } } return instance; } }
静态内部类
public class Singleton { private static class LazyHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return LazyHolder.INSTANCE; } }
标签:
原文地址:http://www.cnblogs.com/JAYIT/p/5051184.html