Technology Sharing

Design pattern usage scenario implementation examples and advantages and disadvantages (creational patterns - singleton pattern, builder pattern, prototype pattern)

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Creational Patterns

Singleton Pattern

The use of the Singleton Pattern in Java is similar to that in other programming languages. Its main purpose is to ensure that a class has only one instance and provide a global access point. The following are some common use cases and detailed explanations of the Singleton Pattern:

scenes to be used

  1. Controlling resource usage

    • Database connection pool:Database connections are expensive resources. Using the singleton pattern can ensure that there is only one connection pool instance, uniformly manage connection resources, avoid repeated creation and destruction of connections, and improve system performance.
    • Thread Pool:The creation and destruction of threads is expensive. The singleton pattern can ensure that there is only one thread pool instance, centrally manage threads, and improve system efficiency.
  2. Global Configuration Management

    • Configuration file management:The configuration in the system is usually global. Using the singleton mode can ensure that the configuration file is only loaded once and shared globally, avoiding resource waste caused by multiple loadings.
    • Log Manager:The logging system is usually global in the application. The singleton mode can ensure the uniqueness of the log manager instance and facilitate unified management of log output.
  3. State Management

    • Cache Management: In some systems, some data needs to be cached. Using the singleton pattern can ensure the uniqueness of the cache manager instance, thereby ensuring the consistency and unified management of the cache.
    • Device Management: For some physical devices, such as printers or serial port devices, the singleton pattern can ensure a unique instance of the device manager to prevent the device from being operated by multiple objects at the same time.

Implementation Example (Java)

Here is an example of implementing the Singleton pattern in Java:

Hungry Singleton Pattern

The hungry singleton pattern creates an instance when the class is loaded:

public class Singleton {
    // 在类加载时创建实例
    private static final Singleton INSTANCE = new Singleton();

    // 私有化构造函数,防止外部实例化
    private Singleton() {}

    // 提供一个公共的访问方法
    public static Singleton getInstance() {
        return INSTANCE;
    }
}