Design Pattern Singleton pattern-PHP source code

Source: Internet
Author: User
Design Pattern-Singleton pattern

I. Overview

The Singleton mode is a common software design mode. Its core structure only contains a special class called singleton class. The Singleton mode ensures that there is only one instance in the system and the instance is easy to access, so as to achieve the purpose of use (for example, in a windows operating system, the task manager can only open one-Main purpose ), it also facilitates the control of the number of instances and saves system resources (benefits beyond the main purpose ). If you want to have only one class object in the system, the singleton mode is the best solution.

II. Introduction

Singleton mode is one of the simplest forms of design patterns. This mode aims to make an object of a class a unique instance in the system. To achieve this, you can start by instantiating the client. Therefore, we need to use a mechanism that only allows the generation of unique instances of the object class to "block" access to all objects to be generated. Use the Factory method to restrict the instantiation process. This method should be a static method (class method), because it is meaningless to let the class instance generate another unique instance.

III. Definitions

Java single-instance mode definition: A class has only one instance and is self-instantiated to provide to the entire system.

IV. motivation

For some classes in the system, it is very important to have only one instance. for example, a system may have multiple print tasks, but only one job is in progress; A system can have only one window manager or file system. a system can have only one timing tool or ID (serial number) generator. For example, only one task manager can be opened in Windows. If you do not use the window object uniqueness mechanism, multiple windows will pop up. if the content displayed in these windows is completely consistent, it is a duplicate object, wasting memory resources; if the content displayed in these windows is inconsistent, it means that the system has multiple states at a certain moment, which is inconsistent with the actual status. it may also cause misunderstandings to the user, and the user does not know which one is the real status. Therefore, it is important to ensure the uniqueness of an object in the system.

How can we ensure that a class has only one instance and this instance is easy to access? Defining a global variable ensures that objects can be accessed at any time, but it cannot prevent us from instantiating multiple objects. A better solution is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance is created, and it can provide a method to access the instance. This is the model motivation of the Singleton mode.

5. key points

Obviously, the singleton mode has three main points:

1. a class can only have one instance;

2. it must create the instance itself;

3. it must provide the instance to the entire system.

From a specific implementation perspective, there are three points:

1. the Singleton mode class only provides private constructor;

2. the class definition contains a static private object of the class;

3. this class provides a static public function to create or obtain its own static private object.

VI. instance

  

This is required when only one instance of a class can be used. Why do we only need one? Some people say it is to save memory, but this is only a benefit of the Singleton mode. Only one instance actually reduces memory usage, but I don't think this is the reason for using the Singleton mode. I think the time to use Singleton mode is when multiple instances may cause program logic errors. For example, how can an ordered number generator be allowed to have multiple numbers in one application? The Singleton mode ensures that only one instance of a Class exists in a Java application.

1. lazy

The difference between lazy and Ele. me is that the time for creating a singleton object is different. "Lazy" is used to create this Singleton object only when you actually use it:

public class SingletonClass{    private static SingletonClass instance=null;    public static SingletonClass getInstance()    {        if(instance==null)        {            synchronized(SingletonClass.class)            {                if(instance==null)                    instance=new SingletonClass();            }        }        return instance;    }    private SingletonClass(){    }}

2. Hunger:

Ele. me: no matter what you are not using, create this Singleton object from the very beginning.

// Some explanations of static in the first line // java allows us to define static classes in a class. For example, the internal class (nested class ). // The class that closes the nested class is called an external class. // In java, we cannot use static to modify top-level classes ). // Only internal classes can be static. Public static class Singleton {// define one of your own instances internally. // The instance can only be called internally. private static final Singleton instance = new Singleton (); private Singleton () {// do something} // Here is a static method for external access to this class. you can directly access public static Singleton getInstance () {return instance ;}}

3. Dual lock format

public static class Singleton{    private static Singleton instance=null;    private Singleton(){        //do something    }    public static Singleton getInstance(){        if(instance==null){            synchronized(Singleton.class){                if(null==instance){                    instance=new Singleton();                }            }        }        return instance;    }}

VII. supplement the role of synchronized?

In the case of multithreading, multiple threads of the same process share the same storage space, which brings convenience while also causing access conflicts. The Java language provides a dedicated mechanism to solve this conflict, effectively avoiding the simultaneous access of the same data object by multiple threads.

Because we can use private keywords to ensure that data objects can only be accessed by methods, we only need to propose a mechanism for methods. this mechanism is the synchronized keyword, which includes two usage methods: synchronized method and synchronized block.

1. synchronized method: declare the synchronized method by adding the synchronized keyword to the method declaration.
For example, public synchronized void accessVal (int newVal); the synchronized method controls access to class member variables: each class instance corresponds to a lock, each synchronized method must obtain the lock of the class instance that calls the method before execution. Otherwise, the thread is blocked. Once the method is executed, the lock is exclusive, the lock is released only when it is returned from this method, and then the blocked thread can obtain the lock and re-enter the executable state. This mechanism ensures that, at the same time, only one of all the member functions declared as synchronized is in the executable state (because at most only one member function can obtain the lock corresponding to this type of instance ), this effectively avoids access conflicts between class member variables (as long as all methods that may be used to invoke class member variables are declared as synchronized ).
In Java, not only are class instances, but each class also corresponds to a lock. in this way, we can declare the static member function of the class as synchronized, to control its access to static member variables of the class.
Synchronized: if a large Method is declared as synchronized, the efficiency will be greatly affected. Typically, if you declare the thread-class method run () as synchronized, since the thread is always running throughout its life cycle, it will never succeed in calling any synchronized method of this class. Of course, we can put the code of the member variable of the category class into a special method, declare it as synchronized, and call it in the main method to solve this problem, but Java provides us with a better solution, that is, the synchronized block.

2. synchronized block: Use the synchronized keyword to declare the synchronized block. Syntax:
Synchronized (syncObject ){
// Code that allows access control
}
The synchronized block is a code block in which the code must obtain the lock of the object syncObject (as described earlier, it can be a class instance or class) before execution. the specific mechanism is described earlier. It is highly flexible because it can target any code block and can specify any locked object.

This problem usually involves multiple threads. if you are learning java multi-thread programming, you are advised to set up an environment and try multiple times of code. many interesting things will be discovered, no matter whether you read a book or Baidu knows that it can help you very little.

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.