Three ways to style a single case:
The first is the simplest, but does not consider thread safety, in multi-threading may be problematic, but I have never seen the phenomenon of error, the table despise me ...
public class Singleton
{
private static Singleton _instance = null;
Private Singleton () {}
public static Singleton CreateInstance ()
{
if (_instance = = null)
{
_instance = new Singleton ();
}
return _instance;
}
}
The second consideration is thread safety, but a bit annoying, but definitely formal, classic
public class Singleton
{
Private volatile static Singleton _instance = null;
private static readonly Object lockhelper = new Object ();
Private Singleton () {}
public static Singleton CreateInstance ()
{
if (_instance = = null)
{
Lock (Lockhelper)
{
if (_instance = = null)
_instance = new Singleton ();
}
}
return _instance;
}
}
The third possibility is that high-level languages such as C # are peculiar, and really lazy
public class Singleton
{
Private Singleton () {}
public static readonly Singleton instance = new Singleton ();
}
First, Singleton (Singleton) mode
The characteristics of the singleton mode:
- A singleton class can have only one instance.
- The Singleton class must create its own unique instance.
- The Singleton class must provide this instance to all other objects.
Single-Case mode application:
- Each computer can have several printers, but only one printer Spooler, preventing both print jobs from being output to the printer at the same time.
- A table with an AutoNumber primary key can be used by multiple users at the same time, but there can be only one place in the database where the next primary key number is assigned. Otherwise, primary key duplication occurs.
Second, Singleton structure of the pattern:
The singleton pattern contains only one character, which is Singleton. Singleton has a private constructor that ensures that the user cannot instantiate it directly through new. In addition, the schema contains a static private member variable instance with the static Public method instance (). The instance method is responsible for verifying and instantiating itself, and then storing it in a static member variable to ensure that only one instance is created. (about threading issues and singleton specific to C # will be discussed in more detail later).
Third, Examples of programs:
The program demonstrates the structure of the Singleton, which itself does not have any real value.
Singleton pattern--Structural Example
Using System;
"Singleton"
Class Singleton
{
Fields
private static Singleton instance;
Constructor
Protected Singleton () {}
Methods
public static Singleton Instance ()
{
Uses "Lazy Initialization"
if (instance = = null)
Instance = new Singleton ();
return instance;
}
}
/**////<summary>
Client Test
</summary>
public class Client
{
public static void Main ()
{
Constructor is protected--cannot use new
Singleton S1 = singleton.instance ();
Singleton s2 = singleton.instance ();
if (S1 = = s2)
Console.WriteLine ("The same instance");
}
}
Four, Under what circumstances is a singleton mode used:
There is a requirement for using the singleton mode: Singleton mode should be used when a system requires only one instance of a class. Conversely, if a class can have several instances coexisting, do not use singleton mode.
Attention:
Do not use singleton mode to access global variables. This violates the intent of the singleton pattern and is best placed in the static member of the corresponding class.
Do not make the database connection a singleton, because a system may have multiple connections to the database, and in the case of a connection pool, the connection should be released as promptly as possible. Singleton mode because of the use of static member storage class instances, it can cause resources can not be released in time, causing problems.
Five, Singleton The realization of the pattern in the real system
The following singleton code shows the load Balancer object. In the load-balancing model, multiple servers are available, and the task allocator randomly picks a server to provide services to ensure that the task is balanced (more complex than this). Here, the task assignment instance can have only one, which is responsible for picking up the server and assigning tasks.
Singleton Pattern-Real World Example
Using System;
Using System.Collections;
Using System.Threading;
"Singleton"
Class LoadBalancer
{
Fields
private static LoadBalancer balancer;
Private ArrayList Servers = new ArrayList ();
Private random random = new random ();
Constructors (protected)
Protected LoadBalancer ()
{
List of available servers
Servers. ADD ("Serveri");
Servers. ADD ("Serverii");
Servers. ADD ("SERVERIII");
Servers. ADD ("Serveriv");
Servers. ADD ("Serverv");
}
Methods
public static LoadBalancer Getloadbalancer ()
{
Support multithreaded applications through
"Double checked locking" pattern which avoids
Locking every time the method is invoked
if (balancer = = null)
{
Only one thread can obtain a mutex
Mutex mutex = new Mutex ();
Mutex. WaitOne ();
if (balancer = = null)
Balancer = new LoadBalancer ();
Mutex. Close ();
}
return balancer;
}
Properties
public string Server
{
Get
{
Simple, but effective random load balancer
int r = Random. Next (servers. Count);
Return servers[R]. ToString ();
}
}
}
/**////<summary>
Singletonapp Test
</summary>
///
public class Singletonapp
{
public static void Main (string[] args)
{
LoadBalancer B1 = Loadbalancer.getloadbalancer ();
LoadBalancer b2 = Loadbalancer.getloadbalancer ();
LoadBalancer B3 = Loadbalancer.getloadbalancer ();
LoadBalancer b4 = loadbalancer.getloadbalancer ();
Same instance?
if (B1 = = b2) && (B2 = = B3) && (b3 = b4))
Console.WriteLine ("Same instance");
Do the load Balancing
Console.WriteLine (B1. Server);
Console.WriteLine (B2. Server);
Console.WriteLine (B3. Server);
Console.WriteLine (B4. Server);
}
}
Six, C # in the Singleton Mode
C # 's unique language features determine that C # has a unique approach to implementing singleton patterns. Here are no more reasons to give a few results:
Method One:
Here's the code to implement the singleton pattern with the advantages of the. NET Framework Platform:
Sealed class Singleton
{
Private Singleton ();
public static readonly Singleton instance=new Singleton ();
}
This reduces the code a lot and also solves the performance penalty caused by threading problems. So how does it work?
Notice that the Singleton class is declared as sealed, which guarantees that it will not be inherited, followed by a instance method that turns the original _instance member variable into public readonly and is initialized at the time of declaration. With these changes, we did get the singleton pattern because, during the JIT process, the. NET Framework initializes this property when the static property in the class is used by any method. The Singleton class instance can then be created and loaded while initializing the instance property. The private constructors and ReadOnly (read-only) guarantee that Singleton will not be instantiated again, which is exactly the intent of the singleton design pattern.
(Excerpt from: http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx)
However, this also brings a number of problems, such as the inability to inherit, the instance is initialized when the program is run, unable to implement deferred initialization and so on.
For details, refer to Microsoft MSDN article: "Exploring the Singleton Design Pattern"
Method Two:
Since there are problems with the method, there are other ways.
Public sealed class singleton
{
singleton ()
{
}
public static singleton getinstance ()
{
return Nested.instance;
}
class nested
{
// explicit static constructor to tell c# compiler
// not to mark type as beforefieldinit
static nested ()
{
}
Internal static readonly singleton instance = new singleton ();
}
}
This enables lazy initialization and has many advantages, but there are also some drawbacks. For more information, please visit implementing the Singleton Pattern in C #. The article contains five kinds of singleton implementations, which are discussed in detail in many aspects, such as mode, thread, efficiency, delay initialization and so on.
Reference Link: http://blog.csdn.net/zhuangzhineng/article/details/3927455
C # design Pattern-Singleton mode