C # Singleton mode

Source: Internet
Author: User

The first contact with Singleton mode is the one that I use OC to implement when I am learning iOS. It was a messy study at the time. I just started to think that C # is not a singleton mode, and later saw a lot of things just found that the original C # also has a singleton mode.

The singleton pattern, as its name implies, has only one instance in the entire program life cycle. So how do you implement it in C #?

Implementing singleton Patterns in C # is a simple matter of testing two things, private constructors, and static objects.

The following code example provides a simple singleton pattern for a class.

 Public class sigle{    privatestatic _sigle=null;     Private Sigle () {}      Public Static sigle getinstance ()    {        if(sigle==null)        {            _sigle=new  sigle ();        }         return _sigle    }}
View Code

Look at the code then let's take a thought.

1. Use private constructors to prevent objects of this class from being created by new.

2. Store objects of this class through private field _sigle.

3, through the common static method getinstance to get to the object of this class.

This getinstance is actually very simple. He will first determine if the private field _sigle has stored the object of this class if it is, then return this object directly if it is not a new object and assign a value to the field _sigle.

Maybe everyone would say why is this new? It's very simple. This is where the private constructor of this class can be called.

As you know, static fields, properties, and methods are all part of the class, and the bucket exists throughout the life of the program, so _sigle can only be assigned once and the class can only create one instance at a time throughout the application life cycle.

C # Singleton 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.