Review C # design pattern-secure Singleton pattern

Source: Internet
Author: User

Singleton pattern ensures that a class can only be instantiated once and provides a global access point to access it.

There are two methods to use the standalone mode.

1. Use a static variable.

2. Use the constructor to judge.

 

First, use the static variable method,

We use an entity instance to determine whether the current class has been instantiated. If not, a singleton instance is added. However, this method is not recommended for everyone. If it is a multi-threaded tool for operation, your concept of monomer will disappear. Therefore, we need to add an object and use a lock to lock the object to prevent multi-thread instantiation. That is, the comments section in.

Private Static readonly object padload = new object ();

Lock (padload)

The second method is to set the constructor as a common method. However, a counter with a static variable is used to restrict the class from being instantiated twice.

 

If the counter is not zero, an exception is thrown to it.

Check the running result:

 

When singleton2 is instantiated multiple times:

 

Throw an exception.

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.