Singleton patterns and common notation analysis (design mode 01)

Source: Internet
Author: User
Ensure that a class has only one instance and provides a global access point for that instance.

--"Design pattern"

The concept of Singleton mode is very simple, the following is the C # language as an example, listing the pros and cons of common single-instance notation.

1. Simple implementation

public sealed class Singleton    {        static Singleton instance = null;        public void Show ()        {            Console.WriteLine (  "instance function");        }        Private Singleton ()        {        } public        static Singleton Instance        {            get            {                if (Instance = = NULL)                {                    instance = new Singleton ();                }                return instance;}}    }

Commentary:


It's unsafe for threads.
The requirements are met in a single thread
Advantages:
Because instances are created inside the Instance property method, classes can use additional functionality
The instantiation is not performed until the object requires an instance to be generated, and this method is called lazy instantiation . Lazy instantiation avoids the instantiation of unnecessary singleton when the application starts.

2. Thread Security

public sealed class Singleton    {        static Singleton instance = null;        private static ReadOnly Object padlock = new Object ();        Private Singleton ()        {        } public        static Singleton Instance        {            get            {                lock (padlock)                {                    if (instance = = null)                    {                        instance = new Singleton ();}                }                return instance;}}    }



Commentary:

The part of the program with the lock at the same time has only one thread to enter
The object instance is created by the first thread that enters the
Later threads enter (instence = = null) as false, and no more object instances are created
Added extra overhead, loss of performance


3. Double Locking

public sealed class Singleton    {        static Singleton instance = null;        private static ReadOnly Object padlock = new Object ();        Private Singleton ()        {        } public        static Singleton Instance        {            get            {                if (Instance = = null)                {                    Lock (padlock)                    {                        if (instance = = null)                        {                            instance = new Singleton ();}                    }                }                return instance;}}    }

Commentary:


Multithreading security
Threads are not locked every time
Allow instantiation to be deferred until the first time an object is accessed


4. Static initialization

public sealed class Singleton    {        private static readonly Singleton instance = null;        Static Singleton ()        {            instance = new Singleton ();        }        Private Singleton ()        {        } public        static Singleton Instance        {            get            {                return Instance;            }        }    }

Commentary:


The dependency common language runtime is responsible for handling variable initialization
public static properties provide a global access point for accessing instances
There is less control over the instantiation mechanism (. NET on behalf of the implementation)
Static initialization is the preferred method of implementing Singleton in. NET

Small bet

Static constructors do not have access modifiers, and C # automatically marks them as private and must be marked as private.

is to prevent developers writing code from calling it, and calls to it are always the responsibility of the CLR.







5. Delay initialization

public sealed class Singleton    {        private Singleton ()        {        } public        static Singleton Instance        {            Get            {                return nested.instance;            }        }        public static void Hello ()        {        }        private class Nested        {            internal static readonly Singleton instance = null;            Static Nested ()            {                instance = new Singleton ();}}    }

Commentary:


Initialization work is done by a static member of the nested class, which enables deferred initialization.

because of the timing of the invocation of a static function, it is called when the class is instantiated or when a static member is called. and the. NET Framework calls the static constructor to initialize the static member variables. So, if you write asphyxication, and then call the Hello method, you instantiate the singleton instance, which is not what we want to see, because we might just want to use the Hello method, not anything else.


Precautions:

1. The instance constructor in singleton mode can be set to protected to allow subclasses to derive.
2, Singleton mode generally do not support the ICloneable interface, because this may lead to multiple object instances, and the original intention of Singleton mode is violated.
3, Singleton mode generally do not support serialization, because it is also possible to cause multiple object instances, as well as the original intention of the singleton model violated.
4. Singletom mode only takes into account the management of object creation, and does not consider the management of object destruction. In terms of the overhead of platforms and objects that support garbage collection, we generally do not need to have special management of their Destruction.


Summarize:

1. Singleton mode is the creation of a restriction rather than an improved class.
2. The core of understanding and extending the singleton pattern is "how to control any call that the user uses new to a constructor of a class."
3, can be very simple to modify a singleton, so that it has a few instances, it is permissible and meaningful.


The above is the singleton pattern and common writing analysis (design mode 01) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.