Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6345a35

Browse files
authored
documentation for Singleton Static Initializer
1 parent d3b974f commit 6345a35

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

CreationalPatterns/Singleton/README.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,33 @@
44

55
## Static Initialization
66

7-
If your applicatioin always creates and uses an instance of the `Singleton` or the overhead of creation and runtime aspects of the Singleton are not onerous, you may want to create your Singleton eagerly, like `ChocolateBoiler_StaticInit.cs`.
7+
:thumbsup: **You may want to create your Singleton eagerly, if**
8+
* your application always creates and uses an instance of the `Singleton`
9+
* the overhead of creation and runtime aspects of the Singleton are not onerous
10+
11+
[ChocolateBoiler_StaticInit.cs](CreationalPatterns/Singleton/ChocolateBoiler_StaticInit.cs).
12+
```cs
13+
public sealed class ChocolateBoiler_StaticInit
14+
{
15+
// singleton instance
16+
private static readonly ChocolateBoiler_StaticInit instance = new ChocolateBoiler_StaticInit();
17+
18+
public static ChocolateBoiler_StaticInit Instance
19+
{
20+
get
21+
{
22+
return instance;
23+
}
24+
}
25+
}
26+
```
827

928
The class is marked as **sealed** to prevent derivation, which could add instances. In addition, the variable is marked **readonly**, which means that it can be assigned only during static Initialization or in a class constructor.
1029

30+
Because the **Singleton** instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the **Instance** property. This solution therefore implements a form of the lazy instantiation property, as in the Design Patterns form of Singleton.
31+
32+
:thumbsdown: **Downside**
33+
* You have less control over the mechanics of the instantiation
34+
35+
Reference:
36+
* MSDN - [Implementing Singleton in C#](https://msdn.microsoft.com/en-us/library/ff650316.aspx)

0 commit comments

Comments
 (0)