2. Singleton single-piece mode for Learning Object-oriented Design Patterns

Source: Internet
Author: User
Singleton single piece (Creation Mode)

1. motivation (Application Scenario ):

In a software system, you must ensure that only one instance exists in the system to ensure logical correctness and good efficiency.

2. Intention:

Ensure that a class has only one instance and provides global access points.

3. Implementation:

Some people may think that to ensure that one class in a system can only have one instance, this class is written as usual, and then you can instantiate it only once in the system?

In fact, this should be the responsibility of the class designer, not the responsibility of the class user.

 

1) Single-threaded Singleton single-piece mode implementation:

Singleton single-piece mode in a single thread can be implemented in two steps.

The first is to add static fields to the constructor to prevent instantiation during use;

The second is to determine whether the object already exists (whether it is null) when obtaining the object value. If it exists, it does not need to be instantiated and directly returns the member of the object. If it does not exist, it is instantiated.

/// <Summary> // Singleton mode in a single thread // [zengwenzhi] 2012-8-3 create /// </Summary> public class Singleton {Private Static Singleton instance; // private constructor to prevent new constructor.
Private Singleton () {}public static Singleton instance {get {If (instance = NULL) {instance = new Singleton () ;}return instance ;}}}

2) Implementation of Singleton single-piece mode under multiple threads:

The lock technology is the key technology of the single-piece Mode Under multithreading. As shown in the following code, in a multi-threaded environment, two threads may run to vertex A at the same time (a \ B: the code has been marked), so that both threads will judge that the instance object is empty. In this way,Both threads run to point B. If there is no B-point code, two instance objects will be created. with B-point code, this problem can be avoided.

 

/// <Summary> // Singleton mode example with multiple threads // [zengwenzhi] 2012-8-3 create /// </Summary> public class singletonm {// volatile as a variable when defined as volatile, the value of this variable is read from momery every time instead of from the cache.
// This is done to ensure that the information for reading this variable is up-to-date, regardless of how other threads update this variable Private Static volatile singletonm instance = NULL; private Static object lockhelper = new object (); Private singletonm () {} public static singletonm instance {get {If (instance = NULL) // a point {lock (lockhelper) // B point {// double check prevents code compilation by optimizing and adjusting the code execution sequence if (instance = NULL) {instance = new singletonm ();}}} return instance ;}}}

3. Singleton single-piece Mode Under the. NET Framework:

/// <Summary> /// Singleton single-piece mode instance // [zengwenzhi] 2012-8-3 create /// </Summary> class program {static void main (string [] ARGs) {//. net Framework Application myclass class1 = new myclass (); myclass calss2 = new myclass (); Type type1 = class1.gettype (); Type type2 = class1.gettype (); // The two outputs are the same. This indicates that there is only one type object of myclass in the world. Console. writeline (type1.tostring (); console. writeline (type2.tostring (); console. Readline () ;}// application class myclass {}

Important statement: This article is the notes recorded by the author when I learned from Mr. Li Jianzhong. The knowledge in this article is not original.

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.