【第22期】观点:IT 行业加班,到底有没有价值?

singleton

原创 2016年08月30日 22:16:48
// It applies only to single-threaded
public sealed class Singleton1
{
	private Singleton1()
	{
	}
	
	private static Singleton1 instance = null;
	public static Singleton1 Instance
	{
		get
		{
			if(null == instance)
				instance = new Singleton1();
			return instance;
		}
	}
}

// It can be used for multi-threaded
public sealed class Singleton2
{
	private Singleton2()
	{
	}

	private static readonly object syncObj = new object();

	private static Singleton2 instance = null;
	public static Singleton2 Instance
	{
		get
		{
			lock(syncObj)// This step spent a lot of time
			{
				if(null == instance)
					instance = new Singleton2();
			}
			return instance;
		}
	}
}

// The better way than the second method
public sealed class Singleton3
{
	private Singleton3()
	{
	}

	private static readonly object syncObj = new object();

	private static Singleton3 instance = null;
	public static Singleton3 Instance
	{
		get
		{
			if(null == instance)
			{
				lock(syncObj)// This step spent a lot of time
				{
					if(null == instance)
						instance = new Singleton3();
				}
			}
			return instance;
		}
	}
}

// The C# language way 
public sealed class Singleton4
{
	private Singleton4()
	{
	}

	private static Singleton4 instance = new Singleton4();
	public static Singleton4 Instance
	{
		get
		{
			return instance;
		}
	}
}

//The C# language way 2
public sealed class Singleton5
{
	Singleton5()
	{
	}

	public static Singleton5 Instance
	{
		get{
			return Nested.instance;
		}
	}

	class Nested{
		static Nested(){}
		internal static readonly Singleton5 instance = new Singleton5();
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

Java Notes 00 - Singleton Pattern(单例总结)

0)Eager initialization [饿汉式]如果程序一开始就需要某个单例,并且创建这个单例并不那么费时,我们可以考虑用这种方式:public class Singleton { p...

java单例模式Singleton的设计

常用版本 public class Singleton { private static Singleton singleton = null; private Singleton() { } public static Singleton getInstanc...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

【剑指offer】题2:实现单件(singleton)模式

实现单件(singleton)模式 单件: 不允许自动生成对象、不允许赋值、拷贝对象:屏蔽构造函数、拷贝构造函数、赋值运算符 加锁并两次判断 互斥量:Mutex +区域锁:socpedlock ...

spring 中属性scope 的prototype(有状态)和singleton(无状态)

  <

singleton的饿汉式,懒汉式及关于双检锁的线程安全模式

关键字: singleton 单例 写法 双锁 线程安全饿汉式单例类 Java代码 复制代码public class Singleton { private Singleton(...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)