Single-Case mode:
Key points: 1, a class has only one instance, 2, the class to create the instance itself, 3, the class itself to the entire system to provide this instance.
Code Show:
namespacesingleton{/// <summary> ///Lazy single case, multithreading security///lazy, do not create an instance when the class loads, so the class loads faster, but the runtime gets the object at a slower speed/// </summary> Public classLazysingleton {Private StaticLazysingleton instance =NULL; //Multithreading Security Private Static ObjectLockObject =New Object(); PrivateLazysingleton () {Console.WriteLine ("private Lazysingleton ()"); } Public StaticLazysingleton Instance {Get { //no need to lock each time to improve efficiency if(Instance = =NULL) { //Multithreading Security Lock(lockobject) {if(Instance = =NULL) { return NewLazysingleton (); } } } returninstance; } } } /// <summary> ///a hungry man single case///initialization is done at class load, so class loading is slow, but getting objects is faster/// </summary> Public classEagersingleton {//readonly allocation of dynamic memory Private Static ReadOnlyEagersingleton instance =NewEagersingleton (); PrivateEagersingleton () {Console.WriteLine ("private Eagersingleton ()"); } Public StaticEagersingleton Instance {Get { returninstance; } } } classProgram {Static voidMain (string[] args) { varLazy =lazysingleton.instance; varEager =eagersingleton.instance; } }}
A singleton model from C # angle lazy and a hungry man