English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Custom Regular Expression Operator =~ Explanation in Swift

This article shares the specific code of the Singleton Pattern in Java design patterns with everyone for reference. The specific content is as follows

Concept:

Singleton Pattern: A class has only one instance.

A class has only one instance and provides a global access point.

The reason for using this pattern is:

  When we are browsing websites, some websites display 'Current Online Users'. Usually, the method to implement this function is to store each logged-in IP address in a memory, file, or database, and with each additional IP, the function 'is implemented.+1is generally implemented by a method, such as add(), to achieve “}}+1function, such as using the 'update' statement, first obtain the data stored in the database, then+1Update the data in the database, then save it; when displaying on the page, you can obtain the data from the database through another method. However, when multiple users log in at the same time, if each one needs to create a new object, then call the execution of the add() method through 'object.methodName', and then store the data in the database, this will lead to multiple users being unable to accurately record actual user data in the database. Therefore, this counter is designed as a global object (everyone uses this object, not a new one), and everyone shares the same data, which can avoid similar problems, which is one of the applications of the singleton pattern. 

Similarly, similar situations and similar ideas will also be encountered in other scenarios. For example:

   1External resources: Each computer has several printers, but only one PrinterSpooler can be used to avoid two print jobs outputting to the printer at the same time. Internal resources: Most software has one (or more) property files to store system configurations, and such a system should have an object to manage these property files.
   2The Task Manager in Windows is a very typical example of the singleton pattern (aren't you familiar with it?). Think about it, can you open two Windows Task Managers? Don't believe it? Try it yourself!
   3The Recycle Bin in Windows is also a typical application of the singleton pattern. Throughout the system operation, the Recycle Bin maintains only one instance.
   4The counter of a website is generally also implemented using the singleton pattern, otherwise it is difficult to synchronize.
   5The logging application of an application generally also uses the singleton pattern for implementation, which is usually due to the shared log file being always open, as only one instance can operate on it, otherwise the content is not easy to append.
   6The reading of configuration objects in web applications generally also applies the singleton pattern, which is because the configuration file is a shared resource.
   7The design of a database connection pool generally also uses the singleton pattern, because a database connection is a type of database resource. In a database software system, using a database connection pool mainly saves the efficiency loss caused by opening or closing database connections, which is very expensive. By maintaining it with the singleton pattern, this loss can be greatly reduced.
   8The design of a thread pool for multi-threading generally also adopts the singleton pattern, which is due to the need for convenient control over the threads in the pool.
   9The file system of an operating system is also a specific example of the singleton pattern implementation, as an operating system can only have one file system.
   10. HttpApplication is also a typical application of the unit instance. Those who are familiar with the entire request lifecycle of ASP.Net (IIS) should know that HttpApplication is also a singleton pattern, and all HttpModules share a single HttpApplication instance. 

In summary, the general application scenarios of the singleton pattern are:

    1. Objects that need to be instantiated frequently and then destroyed.

    2. Objects that take too much time or resources to create but are used frequently.

      3. Stateful utility class objects.

    4. Objects frequently accessing databases or files.

    5. It avoids performance or loss due to resource operations under resource sharing conditions. For example, log files, application configurations, etc.

    6. It is convenient for resource communication under the control of resources, such as thread pools.

Characteristics:

1、The singleton class can only have one instance;

2、The singleton class must create its own unique instance itself;

3、The singleton class must provide this instance to all other objects

Elements of the singleton pattern: 

   1. A private constructor
   2. A private static reference pointing to its own instance
   3. A public static method that returns its own instance 

There are three methods to implement the singleton pattern:

1. Eager汉式: The singleton instance is constructed when the class is loaded, with eager initialization (preloading method).

/**
* Eager汉式 (recommended)
*
*/
public class Test {
    private Test() {
    }
    public static Test instance = new Test();
    public Test getInstance() {
        return instance;
    }
}

Advantages 

    1. Thread-safe
    2. A static object is created at the same time as the class is loaded, and the response speed is fast when called

Disadvantages 

    Resource efficiency is not high, and getInstance() may never be executed. However, if other static methods of the class are executed or the class is loaded (class.forName), the instance will still be initialized

2. Lazy汉式: The singleton instance is constructed when it is first used, with delayed initialization.

class Test {
    private Test() {
    }
    public static Test instance = null;
    public static Test getInstance() {
        if (instance == null) {
       //When multiple threads judge that instance is null, a duplicate situation may occur during the execution of the new operation
            instance = new Singleton2()
        }
        return instance;
    }
}

Advantages 

    It avoids the creation of instances in the饿汉式 when not used, which is resource utilization is high. If getInstance() is not executed, the instance will not be created, and other static methods of the class can be executed.

Disadvantages 

    The lazy汉式 works well in a single thread, but when multiple threads access it simultaneously, it may create multiple instances at the same time, and these multiple instances are not the same object. Although the later created instances will overwrite the earlier ones, there is still a possibility of obtaining different objects. The solution to this problem is to add a lock (synchronized), which may not be fast enough during the first load and has unnecessary synchronization overhead in multithreading.

3.Double check

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

Advantages 

    High resource utilization, not instantiated if getInstance() is not executed, and can execute other static methods of this class

Disadvantages 

    The response is not fast enough when loaded for the first time, due to some reasons of the Java memory model, it occasionally fails

4.Static inner class

class Test {
    private Test() {
    }
    private static class SingletonHelp {
        static Test instance = new Test();
    }
    public static Test getInstance() {
        return SingletonHelp.instance;
    }
}

Advantages 

    High resource utilization, not instantiated if getInstance() is not executed, and can execute other static methods of this class

Disadvantages 

    The response is not fast enough when loaded for the first time

Summary: 

    Generally, the hungry man mode is used, and if you are very concerned about resources, you can use the static inner class. It is not recommended to use the lazy man mode or double detection.

 That's all for this article. I hope it will be helpful to everyone's learning and that everyone will support the Shouting Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

MySql Tutorial