标签:设计模式-单例模式
package com.mycompany.singletondemo; /** * 线程安全 ,饿汉式 * @author Administrator * */ public class Singleton1 { //构造方法私有化 private Singleton1(){} //定义static和final类型的实例对象 private static final Singleton1 instance = new Singleton1(); /* * 通过静态方法获取实例 */ public static Singleton1 getInstance(){ return instance; } }
package com.mycompany.singletondemo; /** * 线程非安全,饱汉式 * @author Administrator * */ public class Singleton2 { //构造方法私有化 private Singleton2(){} //定义变量 private static Singleton2 instance; //定义静态方法获取实例 public static Singleton2 getInstance(){ if (instance == null) { instance = new Singleton2(); } return instance; } }
package com.mycompany.singletondemo; /** * 线程安全,同步方法频繁调用时,效率低,多线程访问不会出现多个实例 * @author Administrator * */ public class Singleton3 { private Singleton3(){} private static Singleton3 instance; public static synchronized Singleton3 getInstance(){ if(instance == null){ instance = new Singleton3(); } return instance; } }
package com.mycompany.singletondemo; /** * 线程安全,效率高,内存占用少 * @author Administrator * */ public class Singleton4 { private Singleton4(){} private static volatile Singleton4 instance; public static Singleton4 getInstance(){ if (instance == null) { synchronized (Singleton4.class) { if (instance == null) { instance = new Singleton4(); } } } return instance; } }
本文出自 “素颜” 博客,谢绝转载!
标签:设计模式-单例模式
原文地址:http://suyanzhu.blog.51cto.com/8050189/1910794