Home  >  Article  >  What is the singleton pattern?

What is the singleton pattern?

Guanhui
GuanhuiOriginal
2020-06-28 17:50:273266browse

The singleton mode is a commonly used software design pattern that creates types. The class created through the method of this mode has only one instance in the current process. Its benefits can ensure that all objects access the unique instance, and reduce Memory overhead and system performance overhead.

What is the singleton pattern?

#The singleton pattern is one of the simplest forms of design patterns. The purpose of this pattern is to make an object of a class the only instance in the system. To achieve this, you start by instantiating it on the client side. Therefore, it is necessary to use a mechanism that only allows the generation of unique instances of the object class, "blocking" all access to the object that is intended to be generated. Use factory methods to limit the instantiation process. This method should be a static method (class method), because there is no point in having an instance of the class generate another unique instance.

How to implement singleton mode

Usually, there are two construction methods for singleton mode in Java language:

  • Lazy style - thread unsafe: The most basic implementation method, thread context singleton, does not need to be shared with all threads, nor does it need to add locks such as synchronize to improve performance.

  • Lazy mode - thread safety: coupled with lazy mode such as synchronize to ensure thread safety, the relative performance is very low, and synchronization is not required most of the time

  • The Hungry Man Way. Refers to the global singleton instance that is constructed when the class is loaded.

  • Double check lock type. On the basis of lazy style, the synchronize keyword and volatile keyword are used to ensure that there is no competition between threads and multiple instances are generated during the first creation. Only the first creation is synchronized, and the performance is relatively high

  • Registration type. Exists as a global property of the created class. The

  • enumeration is created when the created class is loaded. The enumeration class itself in java is also a singleton mode

Recommended tutorial: "PHP"

The above is the detailed content of What is the singleton pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn