欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java单例模式

程序员文章站 2022-07-13 23:46:54
...

下面是三种设计模式的实现。

 

package cn.cnic.lifx.singleton;

public class Singleton 
{
	private Singleton(){ }
	
	private static class SingletonFactory
	{
		static Singleton instance = new Singleton();
	}
	
	public static Singleton getInstance()
	{
		return SingletonFactory.instance;
	}
}

 

 

package cn.cnic.lifx.singleton;

public class Singleton2 
{
	private Singleton2(){ }
	
	private static Singleton2 instance = new Singleton2();
	
	public static Singleton2 getInstance()
	{
		return instance;
	}
}

 

 

package cn.cnic.lifx.singleton;

public class Singleton3 
{
	private Singleton3(){ }
	
	private static Singleton3 instance;
	
	public synchronized static Singleton3 getInstance()
	{
		if(null == instance)
		{
			instance = new Singleton3();
		}
		
		return instance;
	}
}

 

相关标签: Java 设计模式