【IT168 技术】单态定义:Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
Singleton模式就为我们提供了这样实现的可能。使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收(garbage collection)。
使用Singleton注意事项:
有时在某些情况下,使用Singleton并不能达到Singleton的目的,如有多个Singleton对象同时被不同的类装入器装载;在EJB这样的分布式系统中使用也要注意这种情况,因为EJB是跨服务器,跨JVM的
单态模式的演化:
单态模式是个简单的模式,但是这个简单的模式也有很多复杂的东西。
(注意:在这里补充一下,现在单态模式其实有一个写法是不错的见这里:http://www.blogjava.net/dreamstone/archive/2007/02/27/101000.html,但还是建议看完这篇文章,因为解释的事情是不一样的,这里说的是为什么double-checked不能使用.)
一,首先最简单的单态模式,单态模式1。
import java.util.*;
class Singleton
{
private static Singleton instance;
private Vector v;
private boolean inUse;
private Singleton()
{
v = new Vector();
v.addElement(new Object());
inUse = true;
}
public static Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
}
class Singleton
{
private static Singleton instance;
private Vector v;
private boolean inUse;
private Singleton()
{
v = new Vector();
v.addElement(new Object());
inUse = true;
}
public static Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
}
这个单态模式是不安全的,为什么说呢 ?因为没考虑多线程,如下情况:
Thread 1 调用getInstance() 方法,并且判断instance是null,然後进入if模块,
在实例化instance之前,
Thread 2抢占了Thread 1的cpu
Thread 2 调用getInstance() 方法,并且判断instance是null,然後进入if模块,
Thread 2 实例化instance 完成,返回
Thread 1 再次实例化instance
在实例化instance之前,
Thread 2抢占了Thread 1的cpu
Thread 2 调用getInstance() 方法,并且判断instance是null,然後进入if模块,
Thread 2 实例化instance 完成,返回
Thread 1 再次实例化instance
这个单态已经不在是单态。
二,为了解决刚才的问题:单态模式2
public static synchronized Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
采用同步来解决,这种方式解决了问题,但是仔细分析正常的情况下只有第一次时候,进入对象的实例化,须要同步,其它时候都是直接返回已经实例化好的instance不须要同步,大家都知到在一个多线程的程序中,如果同步的消耗是很大的,很容易造成瓶颈。