Singleton is responsible for creating its own unique instance and defining an instance method to allow customers to access the instance.
Iii. Example
Let's take a look at the simplest single-piece mode implementation example.
1 class simplesingleton
2 {
3 privatestatic simplesingleton _ instance;
4
5 private simplesingleton ()
6 {
7}
8
9 publicstatic simplesingleton instance ()
10 {
11if (_ instance = NULL)
12 {
13 _ instance = new simplesingleton ();
14}
15 return _ instance;
16}
17}
Obviously, this implementation method is not thread-safe, and multiple simplesingleton instances may be obtained in a multi-threaded environment. To solve this problem, you can use double negation. First, create a private static variable padlock for the singleton class.
Privatestaticreadonlyobject _ padlock = newobject ();
Then modify the instance method.
1if (instance = NULL)
2 {
3 lock (_ padlock)
4 {
5if (instance = NULL)
6 {
7 instance = new Singleton ();
8}
9}
10}
11 return instance;
In practical applications, the static initialization feature of C # can be used to implement Singleton of thread security.
1 class threadsafesingleton
2 {
3 privatestatic threadsafesingleton _ instance = new threadsafesingleton ();
4
5 private threadsafesingleton ()
6 {
7}
8
9 publicstatic threadsafesingleton instance ()
10 {
11 return _ instance;
12}
13}
This method is relatively simple, but it also has a disadvantage that delayed initialization cannot be implemented. You can create a nested class in the singleton class and use the nested class to implement delayed initialization.