1、单例模式(Singleton):
一个类只会生成唯一的一个对象。保证一个雷仅有一个实例,并提供一个访问它的全局访问点。
2、单例模式的结构图:

3、实现代码如下:
下面提供两种实现方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
class Singleton{ private static Singleton singleton = new Singleton(); private Singleton(){
} public static Singleton getInstance(){ return singleton; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Singleton2{ private static Singleton2 singleton; private Singleton2(){
} public static Singleton2 getInstance(){ if(singleton == null){ singleton = new Singleton2(); } return singleton; } }
|
客户端调用:
1 2 3
| public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); }
|
4、其他说明:
在第二种方法中,即懒汉式,存在线程安全问题。如果有多个线程同时访问该方法,可能会导致多次创建实例,为了解决问题,可以使用对象锁的机制:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Singleton2{ private static Singleton2 singleton; private static Object object = new Object(); private Singleton2(){
} public static Singleton2 getInstance(){ if(singleton == null){ synchronized(object) { if(singleton == null){ singleton = new Singleton2(); } } } return singleton; } }
|
这样就不会出现线程安全问题了。