Home > Java > javaTutorial > body text

Implementation methods and common writing methods of Java singleton pattern

PHPz
Release: 2023-04-27 16:19:07
forward
1415 people have browsed it

1. Hungry mode

Hungry mode is also called preloading mode. It directly creates and initializes a singleton object when the class is loaded, so it does not have thread safety issues. It relies on the ClassLoader class mechanism and is only loaded once when the program starts, so there is no thread safety issue. Its implementation code is as follows:

public class Singleton {
    // 1.防止外部直接 new 对象破坏单例模式
    private Singleton() {}
    // 2.通过私有变量保存单例对象
    private static Singleton instance = new Singleton();
    // 3.提供公共获取单例对象的方法
    public static Singleton getInstance() {
        return instance;
    }
}
Copy after login

Advantages: Implementation Simple and no thread safety issues. Disadvantages: The object is created when the class is loaded. If it is not used after creation, it will cause a waste of resources.

2. Lazy mode

Lazy mode and hungry mode are exactly the opposite. The so-called lazy mode is lazy loading (delayed loading), which means that it is loaded only for the first time. It will be initialized only when used.

Its implementation code is as follows:

public class Singleton {
    // 1.防止外部直接 new 对象破坏单例模式
    private Singleton() {}
    // 2.通过私有变量保存单例对象
    private static volatile Singleton instance = null;
    // 3.提供公共获取单例对象的方法
    public static Singleton getInstance() {
        if (instance == null) { // 第一次效验
            synchronized (Singleton.class) {
                if (instance == null) { // 第二次效验
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
Copy after login

The lazy mode uses double validation locks and volatile to ensure thread safety. ’s , as can be seen from the above code, whether it is hungry man mode or lazy man mode, their implementation steps are the same:

  • Create a private constructor to prevent The new object is used directly in other calling places, so that the object created is not a singleton object.

  • Create a private variable to save the singleton object.

  • Provide a public method to return a singleton object.

Compared with the hungry mode, the lazy mode will not cause a waste of resources, but the writing method is more complicated.

3. Static inner class

Static inner class can ensure both thread safety and lazy loading. It will only pass the ClassLoader mechanism when it is called. to load and initialize the internal static class, so it is thread-safe. The implementation code of this mode is as follows:

public class Singleton {
    // 1.防止外部直接 new 对象破坏单例模式
    private Singleton() {
    }
    // 2.静态内部类
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    // 3.提供公共获取单例对象的方法
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
Copy after login

4. Enumeration

The enumeration is also used for the first time It will be loaded and initialized by the Java virtual machine when used, so it is also thread-safe and lazy-loaded. Its implementation code is as follows:

public enum  EnumSingleton {
    INSTANCE;
    public EnumSingleton getInstance(){
        return INSTANCE;
    }
}
Copy after login

The above is the detailed content of Implementation methods and common writing methods of Java singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!