编程知识 cdmana.com

Design pattern series: Singleton pattern

original : Curly braces MC( WeChat official account :huakuohao-mc). Focus on JAVA Basic programming and big data , Focus on experience sharing and personal growth .

The singleton pattern, as the name suggests , Is to ensure that a class in the system has only one unique object instance . This demand is often encountered in the actual development process .

Singleton mode can be implemented in two ways , One is called Hungry Chinese style , One is called Slacker type .

Let's take a look first UML chart :


Hungry Chinese style

It's called a hungry man , Because this implementation is when the class is loaded Of The object is initialized at the time , And through JVM The class loading mechanism ensures that there is only one class instance in the system .

Let's first look at the complete code of hungry Han style

public class SingleObject {

    //create an object  of SingleObject
    private static SingleObject instance = new SingleObject();

    //make the constuctor private so that this class cannot be instantiated
    private SingleObject(){}

    public static SingleObject getInstance(){
        return instance;
    }

    public void showMessage(){
       System.out.println("I'm eager");
    }
}

The key code of hungry Chinese style is on the first line , adopt static The keyword is decorated instance The variable , This initializes when the class is loaded SingleObject.

Slacker type

The so-called lazy style is to create objects when needed , Lazy style is more complicated , Locking and double checking mechanism is needed to ensure that in multi-threaded environment , Only one instance is created . The complete code is as follows

public class LazySingleObject {

    private volatile static LazySingleObject instance = null;

    private LazySingleObject() {}

    public static LazySingleObject getInstance(){
        // First check
        if (instance == null){
            synchronized (LazySingleObject.class){
               // Second inspection
                if (instance == null){
                    instance = new LazySingleObject();
                }
            }
        }
        return instance;
    }
    
    public void showMessage(){
        System.out.println("I'm lazy");
    }
    
}

This uses the singleton pattern

SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();

summary

The singleton pattern is also one of the creation patterns , When implementing this pattern, the instance variable should be set to static , Second, constructors must become private , Prevent external references and create objects . It's easier to implement the hungry Han style , But initializing the instance object is time-consuming and resource consuming , It will waste time and resources when the system starts up ; Lazy, on the other hand, initializes when needed , It will not occupy system startup resources , But it's more difficult to implement , Especially in the case of multithreading , Unless there are special requirements , Otherwise, it is recommended to use hungry Han style .

Recommended reading

1. Java Concurrent programming things ( Ten )—— Final summary

2. Common network problem location tools that programmers should master

3. Awk Can you use this ancient magic weapon

4. Hand in hand to teach you to build a set of ELK Log search operation and maintenance platform

·END·
 


版权声明
本文为[Curly bracket MC]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145640763r.html

Scroll to Top