一、单例模式的应用场景

  单例模式(singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点。J2EE中的ServletContext,ServletContextConfig等;Spring中的ApplicationContext、数据库连接池等。

二、饿汉式单例模式

  饿汉式单例模式在类加载的时候就立即初始化,并且创建单例对象。它是绝对的线程安全、在线程还没出现以前就实现了,不可能存在访问安全问题。

  优点:没有增加任何锁,执行效率高,用户体验比懒汉式好。

  缺点:类加载的时候就初始化了,用不用都进行,浪费内存。

  Spring 中IoC容器ApplocationContext本身就是典型的饿汉式单例模式:

复制代码
public class HungrySingleton {     private static final HungrySingleton h = new HungrySingleton();      private HungrySingleton() {     }      public static HungrySingleton getInstance() {         return h;     } }
复制代码

  饿汉式单例模式适用于单例对象较少的情况。

三、懒汉式单例模式

  被外部调用才会加载:

复制代码
public class LazySimpleSingleton {     private LazySimpleSingleton() {     }      private static LazySimpleSingleton lazy = null;      public static LazySimpleSingleton getInstance() {         if (lazy == null) {             lazy = new LazySimpleSingleton();         }         return lazy;     } }
复制代码

利用线程创建实例:

复制代码
public class ExectorThread implements Runnable {     @Override     public void run() {         LazySimpleSingleton simpleSingleton = LazySimpleSingleton.getInstance();         System.out.println(Thread.currentThread().getName() + ":" + simpleSingleton);     } }
复制代码

客户端代码:

复制代码
public class LazySimpleSingletonTest {     public static void main(String[] args) {         Thread t1 = new Thread(new ExectorThread());         Thread t2 = new Thread(new ExectorThread());         t1.start();         t2.start();         System.out.println("END");     } }