package lianxi.Singleton; /** * 单例模式的实现,饿汉式,线程安全但效率比较低 */ public class SingletonTest { //定义一个私有构造方法 private SingletonTest() { } //将自身的实例对象设置为一个属性,并加上static和final修饰 private static final SingletonTest instance =new SingletonTest(); //静态方法返回该类实例 public static SingletonTest getInstance() { return instance; } }
package lianxi.Singleton; /** *方法二 * 单例模式的实现:饱汉式,非线程安全 * */ public class SingletonTest2 { // 定义私有构造方法(防止通过 new SingletonTest()去实例化) private SingletonTest2() { } // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) private static SingletonTest2 instance; // 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题) public static SingletonTest2 getInstance() { if (instance == null) instance = new SingletonTest2(); return instance; } }
package lianxi.Singleton; /** *方法三 * 单例模式的实现:饱汉式,线程安全简单实现 * */ public class SingletonTest3 { //定义私有构造方法,(防止SingletonTest3去实例化) private SingletonTest3() { } // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) private static SingletonTest3 instance; // 定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized 避免多线程访问时,可能造成重的复初始化问题) public static synchronized SingletonTest3 getInstance() { if(instance==null) instance =new SingletonTest3(); return instance; } }
package lianxi.Singleton; /** * 方法四 * 单例模式最优方案 * 线程安全 并且效率高 * */ public class SingletonTest4 { // 定义一个私有构造方法 private SingletonTest4() { } //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用) private static volatile SingletonTest4 instance; //定义一个共有的静态方法,返回该类型实例 public static SingletonTest4 getIstance() { // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率) if (instance == null) { //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建) synchronized (SingletonTest.class) { //未初始化,则初始instance变量 if (instance == null) { instance = new SingletonTest4(); } } } return instance; }