一、介绍
单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点。
通常我们可以让一个全局变量使得一个对象被访问,但它不能防止你实例化多个对象。一个最好的办法就是,让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建,并且它可以提供一个访问该实例的方法。
二、实现
public class SingletonExample1 { private SingletonExample1() { } private static SingletonExample1 instance = null; public static SingletonExample1 getInsetance() { if (instance == null) { instance = new SingletonExample1(); } return instance; } } public class SingletonExample2 { private SingletonExample2() { } private static SingletonExample2 instance = new SingletonExample2(); public static SingletonExample2 getInstance() { return instance; } } public class SingletonExample3 { private SingletonExample3() { } private static SingletonExample3 instance = null; public static synchronized SingletonExample3 SingletonExample3() { if (instance == null) { instance = new SingletonExample3(); } return instance; } } public class SingletonExample4 { private static SingletonExample4 instance = null; private SingletonExample4() { } public static SingletonExample4 SingletonExample4() { if (instance == null) { synchronized (SingletonExample4.class) { if (instance == null) { instance = new SingletonExample4(); } } } return instance; } } public class SingletonExample5 { private SingletonExample5() { } private static volatile SingletonExample5 instance = null; public static SingletonExample5 getInstance() { if (instance == null) { synchronized (SingletonExample5.class) { if (instance == null) { instance = new SingletonExample5(); } } } return instance; } } public class SingletonExample6 { private SingletonExample6() { } private static SingletonExample6 instance = null; static { instance = new SingletonExample6(); } public static SingletonExample6 getInstance() { return instance; } } public class SingletonExample7 { private SingletonExample7() { } public static SingletonExample7 getInstance() { return Singleton.INSTANCE.instance; } private enum Singleton { INSTANCE; private SingletonExample7 instance; Singleton() { this.instance = new SingletonExample7(); } } }
其中:SingletonExample1、SingletonExample4线程不安全;