JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Things about the singleton design pattern

Author:JIYIK Last Updated:2025/03/19 Views:

The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one instantiated object. Therefore, we can define the singleton design pattern as follows:

The singleton design pattern is used to restrict a particular object to be created only once and provide shared access to itself to the entire system.

The singleton design pattern generally only allows one instance of itself to be created, so when it is first instantiated, an object is created and stored inside itself. When the object is used next, the object will first check the storage to see if the object has been instantiated. If it already has its own instance, it returns a reference, otherwise it creates an object of its own as described above and stores it inside itself for use by requests.

The principle of the singleton design pattern can be said to be what is mentioned above, and it can be said that it is independent of the programming language. However, due to the differences in the syntax of different programming languages, the implementation of the singleton design pattern is also different. Let's take Java and PHP as examples to illustrate.

For Java, the singleton design pattern can be divided into lazy and hungry styles according to the time when the object is instantiated.

The so-called hungry singleton means that when the singleton class is loaded, it instantiates an object of itself and stores it inside itself.

The code is as follows:

public class Singleton{
         private static Singleton singleton = new Singleton();
         private Singleton(){}
         public static Singleton __Instance(){
                   return singleton;
         }       
}

From the above code, we can see that when the class starts loading, a private static variable singleton is declared, and its own object is instantiated and assigned to the variable singleton. This is the so-called hungry singleton.

The so-called lazy singleton means that it will only instantiate its own object and store it inside itself when the method that generates the instance object is called.

The code is as follows:

public class Singleton {
    private static Singleton singleton;
    private Singleton(){}
    public static synchronized Singleton __Instance(){
        if(singleton==null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

From the above code, we can see that only when the __Instance() method is called, it will first determine whether the variable singleton is empty. If it is not empty, it means that the instantiated object has been created. Otherwise, the instantiated object is created and assigned to the variable singleton.

The above is Java code. Because Java is a compiled language, it supports instantiating the object when the class is loaded.

But for PHP, PHP is an interpreted language. If the class is not loaded, it cannot instantiate the object of the class. Therefore, PHP does not support hungry singletons, which means that the following code has errors and cannot pass.

class Singleton{
         private static $singleton = new self;
         private function __construct(){}
         public static function __Instance(){
                   return self::$singleton;
         }
}

Therefore, PHP only supports lazy singletons, the code is as follows:

class Singleton{
         private static $singleton;
         private function __construct(){}
         public static function __Instance(){
                   if(!self::$singleton instanceof self){
                         self::$singleton = new self;
                   }
                   return self::$singleton;
         }       
}

The most common scenario for using the singleton design pattern is to create a database connection object. The database access object is responsible for creating a database connection instance. Whenever a specific method of the object is called, it will use the connection resource it has already created. It is well known that the cost of creating a database connection resource is very high (it takes a lot of time and resources). Therefore, when designing the code, you should create as few database connection resources as possible.

In most cases, after the data in the database is retrieved, there is no need to keep the database connection resources and they can be released. In view of this situation, it makes sense to make the database access object a singleton. Every time a new data operation requires a new database access object, the previous object will be reused, and there is no need to instantiate a new database access object to establish additional database connection resources.

Therefore, we can know that using the singleton design pattern can save memory space, avoid repeated creation and destruction of objects, improve performance, and so on.

Because the singleton design pattern is often used to connect to the database, I wrote a class for operating the database, and tried to use the singleton design pattern when designing the class.

The source code is hosted on github , and there is a brief introduction to the use of the class functions. Everyone is welcome to download it.

 

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Strategy Design Pattern and Open-Closed Principle in Java

Publish Date:2025/03/19 Views:114 Category:ALGORITHM

The Strategy design pattern is based on the Open/Closed design principle , the famous " O SOLID " of design principles . It is one of the patterns that has become popular in the field of object-oriented analysis and design, along with the D

How to implement the singleton pattern in JavaScript ES6+

Publish Date:2025/03/19 Views:55 Category:ALGORITHM

In this article, we will show you how to implement the singleton pattern in JavaScript. If we are a full-stack JavaScript developer, we know that JavaScript is a powerful language and we can build amazing websites with it. On the other hand

How to use the Adapter design pattern in Java

Publish Date:2025/03/19 Views:77 Category:ALGORITHM

The Adapter design pattern in Java , also known as the Wrapper pattern, is another very useful GOF pattern that helps bridge the gap between two classes in Java. According to the Gang of Four pattern list, Adapter is a structural pattern, m

Java Decorator Design Pattern Example

Publish Date:2025/03/19 Views:116 Category:ALGORITHM

Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is alway

How to implement the Command Design Pattern in Java

Publish Date:2025/03/19 Views:178 Category:ALGORITHM

Hello everyone, today, we will learn an important design pattern which is often overlooked by Java developers. Yes, I am talking about the Command pattern which helps us write flexible and loosely coupled code to implement actions and event

How to use the State Design Pattern in Java?

Publish Date:2025/03/19 Views:146 Category:ALGORITHM

The State design pattern is a behavioral pattern. The State pattern looks similar to the Strategy pattern, but it helps in managing the object states so that they behave differently in different states. In this example, we will take a famou

Observer Design Pattern in Java

Publish Date:2025/03/19 Views:71 Category:ALGORITHM

Observer design pattern in Java is a basic core Java pattern where the Observer monitors any changes in the state or properties of the Subject . For example, a company updates all shareholders about any decision taken by them here the compa

How to use Composite Design Pattern in Java?

Publish Date:2025/03/19 Views:181 Category:ALGORITHM

Hello Java programmers, if you want to learn about Composite Design Pattern in Java , such as how to implement Composite Design Pattern and when to use it, then you have come to the right place. In this article, we will discuss Composite De

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial