This article first discusses the single piece Singleton, the goal of a single piece is to ensure that a type has only one instance, then who will guarantee the uniqueness of the instance? Possible scenarios are:
A) The caller-side guarantee.
When the caller invokes a class, he does not need to consider whether the class has been instantiated. And it would be irresponsible to hand over such regulatory work to the caller.
b) Type of internal assurance.
How to guarantee within the type?
Put the instance creation work into the type so that the type can regulate the creation of the instance. A type can know whether an internal instance has been created, or even how many times the work of creating the instance has been executed.
So the individual believes that understanding a single piece needs to be divided into two steps:
1, supervision work who will do? The regulatory work of an instance requires the type to do it yourself.
2. How does supervision work? Type how to ensure that an instance is the only technology implementation problem, you can see the version of the thread safe, dual-locked, delayed initialization, and so on.
The following is a step-by-step analysis of how instantiation work is placed within a type using pseudo code.
Call me, instance I give you
class Singleton
{
Singleton Instance = null;
// 实例化类型 Singleton
Singleton GetInstance()
{
Instance = new Singleton();
return Instance;
}
}
You just call, I guarantee the only
class Singleton
{
Singleton Instance = null;
//实例化类型 Singleton
Singleton GetInstance()
{
Instance = new Singleton();
return Instance;
}
// 实例化类型 Singleton,实例化时判断类型有没有被创建过,这样就保证了实例的唯一
Singleton GetInstance()
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}
You can all call, I need to count the number of calls
class Singleton
{
Singleton Instance = null;
public int Count { get; set; }
//实例化类型 Singleton
Singleton GetInstance()
{
Instance = new Singleton();
return Instance;
}
// 实例化类型 Singleton,实例化时判断类型有没有被创建过,这样就保证了实例的唯一
Singleton GetInstance()
{
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
// 实例化类型 Singleton,并且加入一个计数器,这样能知道实例化工作被执行了多少次
Singleton GetInstance()
{
Count++;
if (Instance == null)
{
Instance = new Singleton();
}
return Instance;
}
}