Java单例模式的实现

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。如果我们要让类在一个虚拟机中只能产生一个对象,我们首先必须将类的构造方法的访问权限设置为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”。




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值