所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。如果我们要让类在一个虚拟机中只能产生一个对象,我们首先必须将类的构造方法的访问权限设置为private,这样,就不能用new操作符在类的外部产生类的对象了,但在类内部仍可以产生该类的对象。因为在类的外部开始还无法得到类的对象,只能调用该类的某个静态方法以返回类内部创建的对象,静态方法只能访问类中的静态成员变量,所以,指向类内部产生的该类对象的变量也必须定义成静态的。
单例模式的“饿汉式”实现:
public class TestSingletonHungry
{
public static void main(String[] args)
{
SingletonHungry singletonHungry1 = SingletonHungry.getSingleton();
SingletonHungry singletonHungry2 = SingletonHungry.getSingleton();
//判断两个对象的内存地址是否相同
System.out.println(singletonHungry1 == singletonHungry2);
}
}
//单例模式的“饿汉式”实现
class SingletonHungry
{
//私有化构造器,使得类的外部不能创建该类的对象
private SingletonHungry(){}
//在类的内部创建一个类的实例
private static SingletonHungry singleton = new SingletonHungry();
//此公共方法只能通过类来调用
public static SingletonHungry getSingleton()
{
return singleton;
}
}
单例模式的“懒汉式”实现:
public class TestSingletonLazy
{
public static void main(String[] args)
{
SingletonLazy singletonLazy1 = SingletonLazy.getSingleton();
SingletonLazy singletonLazy2 = SingletonLazy.getSingleton();
//判断两个对象的内存地址是否相同
System.out.println(singletonLazy1 == singletonLazy2);
}
}
//单例模式的“懒汉式”实现(如下程序存在线程安全问题)
class SingletonLazy
{
//1.将构造器私有化,保证在此类的外部,不能调用本类的构造器
private SingletonLazy(){}
//先声明类的引用
private static SingletonLazy singleton = null;
public static SingletonLazy getSingleton()
{
//如果类的实例未创建,那些先要创建,然后返回给调用者
if(singleton == null)
{
singleton = new SingletonLazy();
}
//若有了类的实例,直接返回给调用者
return singleton;
}
}
解决“懒汉式”存在的线程安全问题,将代码修改如下:
public class TestSingletonLazy
{
public static void main(String[] args)
{
SingletonLazy singletonLazy1 = SingletonLazy.getSingleton();
SingletonLazy singletonLazy2 = SingletonLazy.getSingleton();
//判断两个对象的内存地址是否相同
System.out.println(singletonLazy1 == singletonLazy2);
}
}
//单例模式的“懒汉式”实现
class SingletonLazy
{
//1.将构造器私有化,保证在此类的外部,不能调用本类的构造器
private SingletonLazy(){}
//先声明类的引用
private static SingletonLazy singleton = null;
public static SingletonLazy getSingleton()
{
//增加判断,减少可能存在的其他线程的等待,从而提高效率
if(singleton == null)
{
//利用锁维护线程安全
synchronized (SingletonLazy.class)
{
//如果类的实例未创建,那些先要创建,然后返回给调用者
if(singleton == null)
{
singleton = new SingletonLazy();
}
}
}
//若有了类的实例,直接返回给调用者
return singleton;
}
}
运行程序后发现返回结果都为“true”。