One, Singleton mode (Singleton)

Source: Internet
Author: User

The initial definition of the singleton pattern appears in design mode (Eddisonvis, 1994): "Guarantees that a class has only one instance, and provides a global access point to access it." ”

Features: First, there can only be one instance of a class;

The second is that it must create this instance on its own;

Thirdly, it must provide this instance to the whole system on its own.

First, the classic realization

usingSystem;namespacesingletonpattern{//Classic notation//sealed prevent other classes from inheriting from this class     Public Sealed classClassicalsample {//used to save unique instances        Private Staticclassicalsample _classicalsample; //Lock Range        Private Static ReadOnly Objectobj =New Object(); //private constructors to prevent external new instantiation        PrivateClassicalsample () {Console.WriteLine ("instantiation of"); }        //unify this class of         Public Staticclassicalsample getinstance () {//reduce the cost of locks            if(_classicalsample = =NULL)            {                //Prevent multithreading concurrency                Lock(obj) {//                     if(_classicalsample = =NULL) {_classicalsample=Newclassicalsample (); }}} Console.WriteLine ("Get Instance"); return_classicalsample; }    }}

Second, the static constructor implementation

usingSystem;namespacesingletonpattern{ Public Sealed classStaticconstructorsample {Private Staticstaticconstructorsample _staticconstructorsample; PrivateStaticconstructorsample () {Console.WriteLine ("instantiation of"); }        //Static constructors: Executes at first use and executes only once        Staticstaticconstructorsample () {_staticconstructorsample=Newstaticconstructorsample (); Console.WriteLine ("Static constructor instantiation"); }         Public Staticstaticconstructorsample getinstance () {Console.WriteLine ("Get Instance"); return_staticconstructorsample; }    }}

Third, static variable implementation

usingSystem;namespacesingletonpattern{ Public Sealed classStaticvariablesample {Private Static ReadOnlyStaticvariablesample _staticvariablesample =Newstaticvariablesample (); PrivateStaticvariablesample () {Console.WriteLine ("instantiation of"); }         Public Staticstaticvariablesample getinstance () {Console.WriteLine ("Get Instance"); return_staticvariablesample; }    }}

Test:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespacesingletonpattern{classProgram {Static voidMain (string[] args)            {classicalsampletest ();            Staticconstructorsampletest ();            Staticvariablesampletest ();        Console.read (); }        Static voidClassicalsampletest () {Console.WriteLine ("Classic single-case mode test"); TaskFactory TaskFactory=NewTaskFactory (); //task groups for multithreaded testinglist<task> tasks =NewList<task>(); //Each thread gets the instance setlist<classicalsample> list =NewList<classicalsample>();  for(inti =0; I < -; i++) {tasks. ADD (Taskfactory.startnew<ClassicalSample> (() = Classicalsample.getinstance ()). ContinueWith ((r) ={list.                ADD (R.result);            })); } taskfactory.continuewhenall (Tasks. ToArray (), p={Console.WriteLine (""); Console.WriteLine ("a total of {0} occurrences were obtained after the tasks group execution was completed", P.count ()); Console.WriteLine ("number of instances {0}", List. Distinct ().            Count ());        }); }        Static voidStaticconstructorsampletest () {Console.WriteLine ("Static constructor Single-instance mode test"); TaskFactory TaskFactory=NewTaskFactory (); //task groups for multithreaded testinglist<task> tasks =NewList<task>(); //Each thread gets the instance setlist<staticconstructorsample> list =NewList<staticconstructorsample>();  for(inti =0; I < -; i++) {tasks. ADD (Taskfactory.startnew<StaticConstructorSample> (() = Staticconstructorsample.getinstance ()). ContinueWith ((r) ={list.                ADD (R.result);            })); } taskfactory.continuewhenall (Tasks. ToArray (), p={Console.WriteLine (""); Console.WriteLine ("a total of {0} occurrences were obtained after the tasks group execution was completed", P.count ()); Console.WriteLine ("number of instances {0}", List. Distinct ().            Count ());        }); }        Static voidStaticvariablesampletest () {Console.WriteLine ("static variable single-case mode test"); TaskFactory TaskFactory=NewTaskFactory (); //task groups for multithreaded testinglist<task> tasks =NewList<task>(); //Each thread gets the instance setlist<staticvariablesample> list =NewList<staticvariablesample>();  for(inti =0; I < -; i++) {tasks. ADD (Taskfactory.startnew ()= Staticvariablesample.getinstance ()). ContinueWith ((r) ={list.                ADD (R.result);            })); } taskfactory.continuewhenall (Tasks. ToArray (), p={Console.WriteLine (""); Console.WriteLine ("a total of {0} occurrences were obtained after the tasks group execution was completed", P.count ()); Console.WriteLine ("number of instances {0}", List. Distinct ().            Count ());        }); }    }}

One, Singleton mode (Singleton)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.