Ensure a class has only instance ,and provide a global point of access to it.
单例模式:就是让一个类只能产生一个实例。
单例模式有两种形式:
1,饿汉式:类加载时,就能就行实例化(也就是说这个类能产生唯一的对象)。
public class Singleton
{
//饿汉式单例模式的实现
//类加载时直接实例化
private static Singleton m_instance = new Singleton();
private Singleton()
{
}
public static Singleton getInstance()
{
return m_instance;
}
}
2,懒汉式:第一次引用类时,才能进行实例化。
public class Singleton
{
// 懒汉式单例模式
private static Singleton _instance = null;
private Singleton ()
{
}
synchronized public static Singleton getInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
从上面的代码中可以看出,单例模式一个很重要的特点就是构造函数的修饰符是私
有的,这样就能生成一个对象,从而避免了外界利用构造函数创建出很多个例子。
synchronized是对getInstance()方法进行了同步限制,如果这个getInstance(
)方法未被同步化,如果有两个线程同时调用此方法,if(_instance == null)
成立,那么这两个线程都会创建一个对象,从而不同实现单利模式。
单例模式应用的示例:
public class GlobalNum
{
private static GlobalNum gn = new GlobalNum();
private int num = 0;
public static GlobalNum getInstance()
{
return gn;
}
public synchronized int getNum()
{
return ++num;
}
}
public class SingleDemo
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
//实现线程A
NumThread threadA = new NumThread("线程A");
//实现线程B
NumThread threadB = new NumThread("线程B");
//启动线程
threadA.start();
threadB.start();
}
}
class NumThread extends Thread
{
private String threadName;
public NumThread(String name)
{
threadName = name;
}
//实现run()方法
public void run()
{
GlobalNum gnObj = GlobalNum.getInstance();
//循环访问,输出访问次数
for(int i = 0;i< 5;i++)
{
System.out.println(threadName + "第" + gnObj.getNum() + "次访问!");
try
{
this.sleep(1000);
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
}
}