Home >Java >javaTutorial >How to implement the singleton pattern of Java creational design pattern

How to implement the singleton pattern of Java creational design pattern

PHPz
PHPzforward
2023-05-15 10:49:05796browse

Introduction

The singleton pattern is a creational design pattern. Its main features include:

  • Only one instance: The singleton pattern ensures that there is only one instance in the system. The instance object exists, and all access to the object is a reference to the same object

  • Global access: Singleton mode can globally access the instance object, avoiding the need for multiple objects to interact with each other. Conflicts and competition

  • Delayed initialization: Singleton mode usually uses delayed initialization technology, and only creates singleton objects when needed, avoiding unnecessary waste of resources and performance losses, ensuring Correctness and reliability of singleton objects

  • Thread safety: Singleton mode needs to consider thread safety issues to ensure that the instance object obtained under multi-threads is the same, avoiding multi-threading Competition and conflict between

Advantages

  • Provides a globally unique instance to facilitate the management and maintenance of objects

  • Reduces the creation and destruction of objects and improves system performance.

  • Avoids competition and conflicts between multiple instances and ensures the consistency and stability of object states Property

  • Can control the number of instances of a certain class in the system to avoid waste and abuse of system resources

  • Facilitates thread safety and serialization , Reflection and other functions improve the reliability and security of objects

Disadvantages

  • The singleton mode will increase the complexity of the code and increase It reduces the difficulty of system maintenance and code testing.

  • The singleton mode may cause the life cycle of the singleton object to be too long, resulting in the object not being released in time, thus affecting the performance of the system

  • The singleton mode may be abused, resulting in too many singleton objects in the system, thereby increasing the occupation of system resources and the difficulty of management

  • The singleton mode may be destroyed, especially in multi-threaded environments, special implementation methods are needed to ensure the correctness and reliability of singleton objects

Implementation

热汉式

This is the simplest singleton implementation method. In this method, the singleton instance is created when the class is loaded, so it can be guaranteed to be safe in a multi-threaded environment.

package com.fanqiechaodan.singleton.singleton1;
/**
 * @Classname Singleton
 * @Description
 */
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton(){
        // 私有构造函数
    }
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

Lazy Man Style

In this method, the singleton instance is created when it is used for the first time. In a multi-threaded environment, the use of double locking mechanism can ensure that only one instance is created .

package com.fanqiechaodan.singleton.singleton2;
/**
 * @Classname Singleton
 * @Description
 */
public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {
        // 私有构造函数
    }
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Static inner class

This method takes advantage of Java's class loading mechanism. The Singleton instance will be loaded only when the SingletonHolder class is accessed for the first time. This method ensures thread safety. , and can implement lazy loading

package com.fanqiechaodan.singleton.singleton3;
/**
 * @Classname Singleton
 * @Description
 */
public class Singleton {
    private Singleton(){
        // 私有构造函数
    }
    public static Singleton getInstance(){
        return SingletonHolder.INSTANCE;
    }
    private static class SingletonHolder{
        private static final Singleton INSTANCE = new Singleton();
    }
}

Enumeration

Using enumeration types can very conveniently implement thread-safe singleton mode. The enumeration is created when it is defined, so it is Thread-safe, and there is only one instance.

package com.fanqiechaodan.singleton.singleton4;
/**
 * @Classname Singleton
 * @Description
 */
public class Singleton {
    private Singleton() {
        // 私有构造函数
    }
    static enum SingletonEnum {
        /**
         * 枚举实例
         */
        INSTANCE;
        private Singleton singleton;
        /**
         * 私有构造函数,确保只有一个实例
         */
        private SingletonEnum() {
            singleton = new Singleton();
        }
        private Singleton getSingleton() {
            return singleton;
        }
    }
    /**
     * 对外暴露一个获取Singleton对象的静态方法
     *
     * @return
     */
    public static Singleton getInstance() {
        return SingletonEnum.INSTANCE.getSingleton();
    }
}
  • Hungry-style implementation is simple, but does not support delayed loading. When the application starts, the instance object is created

  • The lazy style supports lazy loading, but it requires the use of a double-check lock mechanism and the code is relatively complex

  • Static inner classes are a simple, thread-safe implementation method , and also supports delayed loading

  • The enumeration type is the simplest singleton implementation method and the safest. It does not need to consider thread safety issues and also supports delayed loading.

Generally speaking, the enumeration singleton mode is a simple, efficient and thread-safe singleton implementation method that can meet the needs of most singleton modes. Therefore, in actual development , it is recommended to use the enumeration singleton mode to implement the singleton mode.

The above is the detailed content of How to implement the singleton pattern of Java creational design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete