Single-Case mode

Source: Internet
Author: User

As for design patterns, it must be understood that design patterns are a set of reusable, most well-known, categorized purposes, code design experiences. Design patterns are used to reuse code, make code easier for others to understand, ensure code reliability, and be easy to maintain. Of course this is the encyclopedia's explanation.

Some are called design patterns, and personal understanding is a standard design experience or programming skill that most programmers summarize for specific problems. Now, there are 23 of the more famous

Create type

1. Factory method (Factory methods)

2. Abstract Factory (Abstraction Factory)

3. Builder (Builders)

4. Prototype (prototype)

5. Singleton (single case)

Structural type

6. Adapter Class/object (Adapter)

7. Bridge (Bridging)

8. Composite (Combination)

9. Decorator (decoration)

Facade (appearance)

Flyweight (enjoy Yuan)

Proxy (agent)

Behavioral type

Interpreter (interpreter)

Template method

Chain of Responsibility (Chain of responsibility)

Command (commands)

Iterator (iterator)

Mediator (intermediary)

Memento (Memorandum)

OBSERVER (Observer)

(state)

Strategy (strategy)

Visitor (visitor)

Single case Mode Singleton

Intent: Ensure that a class has only one instance and provides a global access point to access it. Applicability: When a class can have only one instance and the customer can access it from a well-known access point. When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.

Suitable for scenes with only one object only one object is required during the entire program run, requiring that the object be instantiated only once. such as printer connection, database connection pool, thread pool, write log object.

The first form of a notation

 Public Sealed classsingleton{Private Static intBuildcount=0;Private Static intCreatecount=0;Private Static intMethodcount=0;//internal static ObjectsPrivate StaticSingleton singleton=NULL;//privatization constructor, do not let outside create objectPrivateSingleton () {Singleton.buildcount++; Console.WriteLine ("{0} times execution Constructor", Singleton.buildcount);}//static methods Get Object Instances Public StaticSingleton CreateInstance () {
if (singleton==null)
{Singleton=NewSingleton ();
}singleton.createcount++; Console.WriteLine ("{0} times execution CreateInstance", singleton.createcount);returnSingleton;} Public voidLog () {Singleton.methodcount++; Console.WriteLine ("I am the {0} call, but I am the object of the {1} secondary constructor", Singleton.methodcount,singleton.buildcount);} }}
class program{staticvoid Main (string[] args) {

for (int i=0;i<9;i++)
{
Singleton.createinstance ();
}


}

Once a single-threaded execution, you will find that the constructor is executed only once, and the static instance method executes many times, that is, the equivalent of an instantiation once, then you think has been completed, actually did not implement.

class program{staticvoid Main (string[] args) {
TaskFactory task=new TaskFactory ();
for (int i=0;i<9;i++)
{
Singleton.createinstance ();//Single thread

task. StartNew (() =singleton.createinstance ());//Multithreading
}console.readkey ();}}

After multithreaded execution, you will find that 3 or 4 constructors have been executed, stating that it is not a singleton. Why this is performed 4 times, not 10 times, this is actually related to multithreading, we say the execution process, first we prepared 10 threads to create objects, multithreading is concurrent execution, all come in to determine whether the object is null, and our computer is generally 4 threads, So only 4 line inlet to judge the object null, also executed 4 times the constructor, if the computer is fast enough can be 8 or 10 times.

We'll add a lock to the static method.

 Public Sealed classsingleton{Private Static intBuildcount=0;Private Static intCreatecount=0;Private Static intMethodcount=0;//internal static ObjectsPrivate StaticSingleton singleton=NULL;//privatization constructor, do not let outside create objectPrivateSingleton () {Singleton.buildcount++; Console.WriteLine ("{0} times execution Constructor", Singleton.buildcount);}Private Static Objectsingleton_lock=New Object();//static methods Get Object Instances Public StaticSingleton CreateInstance () {Lock(singleton_lock) {if(singleton==NULL) {Singleton=NewSingleton (); }} Singleton.createcount++; Console.WriteLine ("{0} times execution CreateInstance", Singleton.createcount); returnSingleton;} Public voidLog () {Singleton.methodcount++; Console.WriteLine ("I am the {0} call, but I am the object of the {1} secondary constructor", Singleton.methodcount,singleton.buildcount);} }}

It's perfectly possible, but it's not perfect, we should add another layer of judgment.

//static methods Get Object Instances Public StaticSingleton CreateInstance () {if(singleton==NULL){   Lock(singleton_lock) {if(singleton==NULL) {Singleton=NewSingleton (); } }} singleton.createcount++; Console.WriteLine ("{0} times execution CreateInstance", Singleton.createcount); returnSingleton;}

Why add another layer of judgment, in the multi-threaded case you will find that at the same time there are 4 processes into the lock, when only one process to create, and other processes to create the discovery has been created, will be returned, and this will waste process wait time. If there is another multi-threaded to create the object, it is obvious that the previous object has been created, there will still be 4 processes to wait. So the if judgment in the outer layer not only determines whether the object is empty, but more importantly, after the first creation, no longer waits for the lock, and if the inside is guaranteed by the singleton implementation.

The second type of notation

The main use of language features, static constructors: The class is used for the first time when it is executed, and only once

 public  class   singleton{ //  internal static object  private  static  Singleton singleton= ;  //  privatization constructor, do not let outside create object  private   Singleton () {  //Static constructor: Executes when the class is first used, and executes only once  static   Singleton () { singleton  =new   Singleton ();   
Static method Gets the object instance public static Singleton CreateInstance () { return Singleton;}  

The third kind of wording

 public  class   singleton{ //  internal static objects are created only once, in memory and only one  private  static readonly  Singleton singleton=new Singleton ()   //  privatization constructor, do not let outside create object  private   Singleton () {}  //  static method gets the object instance  public  static   Singleton CreateInstance () { return " Span style= "color: #000000;" > Singleton;} }  

Of course, the third you can directly open the static object, but it is not recommended to use, if you want to use a certain permissions to control.




Single-Case mode

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.