Location>code7788 >text

The Monocle Pattern and its Ideology

Popularity:40 ℃/2024-08-01 22:37:20

This article includes the following points ↓

在这里插入图片描述

reach a verdictdesign patternRather than simply applying a fixed code framework to a project, anrigorous programming thinking, designed to provide experience and guidance in solving specific problems.

Singleton Pattern

schematic diagram

Designed to ensure that there is only one instance of the class and to provide a global access point to that instance.

suitability

When you want to have only one instance in the system and need to be able to access that instance from anywhere globally.

When you need to tightly control the instantiation process of a class to ensure that all code uses the same instance.

summarize

The core idea of the singleton pattern is to control objectsInstantiate only onceand provide aglobal access pointto get to that instance. This ensures that there is only one instance in the system and that all access to that instance is through the same access point.

There are several ways to implement the singleton pattern, unfolded through the following examples.

simple case

Six common implementations of the singleton pattern, one by one to analyze their characteristics and applicable scenarios:

  1. Slacker style threads are not safe:

source code (computing)

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  

    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}

Features: Lazy loading to create instantiated objects on first use. In multi-threaded environments, concurrency issues may arise, resulting in the creation of multiple instances.

Applicable Scenarios: Simple applications in single-threaded environments, scenarios that do not have high performance requirements and do not use singletons frequently.

  1. Slacker-style thread safety

source code (computing)

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

Features: It is also lazy loading, but uses the synchronized keyword to ensure thread safety. However, this can cause performance degradation because a lock is required every time the instance object is fetched.

Applicable Scenarios: Used in multi-threaded environments, scenarios with low performance requirements, or where concurrency requirements are not particularly high.

  1. Hungry Man Style

source code (computing)

public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
        return instance;  
    }  
}

Features: Instantiated objects are created when the class is loaded, so there are no multi-threaded safety issues and access is efficient. However, memory may be wasted because instances are created at program startup and occupy memory even if they are not used.

Applicable Scenarios: Scenarios that do not require much memory footprint and want to initialize the singleton at program startup.

  1. Double Check Lock/Double Check Lock

source code (computing)

public class Singleton {  
    private volatile static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized () {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

Features: By double-checking locking, both lazy loading and thread-safety are achieved, and unnecessary lock contention is avoided when instances have already been created, resulting in higher performance.

Applicable Scenarios: Scenarios with high performance requirements and lazy loading, especially in multi-threaded environments.

  1. Registered/static inner classes

source code (computing)

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
        return ;
    }
}

Features: Lazy loading is achieved through static inner classes and is thread-safe. It is not initialized when the class is loaded, but only when the first call to thegetInstance() method before it is initialized.

Applicable Scenarios: Scenarios that have memory footprint requirements and want to initialize only on first use.

  1. enumerated class (math.)

source code (computing)

public enum Singleton {
    INSTANCE;
//  private Singleton(){}
    public Singleton getSelf() {
        return INSTANCE;
    }
}
public static void main(String[] args) {
    Singleton instance = ;
}

Features: Implementing a single instance using an enumerated type takes advantage of the fact that the nature of enumerations ensures that only one instance will exist in any case. Instances of enumerated classes are initialized when the class is loaded.

Applicable Scenarios: Scenarios that don't require too much memory footprint and want to implement singleton in a clean and concise way. Enumerated classes are also thread-safe.

The enumeration class itself is a singleton instance = ; and can have multiple enumerations.INSTANCE,TWO;The INSTANCE in the enumerated class is the Singleton object instance, as you can tell by looking at the getSelf method that doesn't report an error; the enumerated classThe constructor itself is private, the result of the annotation in the liberalization example is the same; the enumeration in themethodologiesIt can only be called by means of (), which is a manifestation of singleton.

This is the best way to implement the singleton pattern, which is more concise, automatically supports serialization mechanisms, and absolutely prevents multiple instantiations. However, private constructors cannot be called via reflection.

Application in Spring Framework?

The Spring Framework uses the idea of the singleton pattern in a number of ways, and it is widely used to manage and create bean instances.By default, the Spring container configures all beans as singletons, which means that there is only one instance of each bean that exists in the entire application. This default singleton pattern ensures performance and resource utilization of the Spring application.

In a Spring context, this is accomplished by using the@Bean@Component@Service@Repository etc. annotations or explicitly declaring the bean in the configuration file, Spring automatically configures it to be in singleton mode, i.e., only one instance is created in the entire application. For example, configure class creation.

Example: Database connection configuration class

@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        ("");
        ("jdbc:mysql://localhost:3306/mydatabase");
        ("username");
        ("password");
        return dataSource;
    }
}

Is this singleton pattern in the Spring Framework using the singleton design pattern to create beans?

Obviously not. The most notable point is, are the constructor methods of the classes you create in your project private?

Spring underlying the creation of a singleton pattern of beans using the BeanFactory factory design pattern to create, do not get confused here. A more accurate description of this bean concept should be the bean'ssingleton scope

In addition to this, the Spring Framework provides other types of scopes such asPrototypeThe prototype mode, which can be accessed through the@Scope("prototype") annotation to label a bean so that each time the bean is retrieved from the container, the container creates a new instance.

@Component
@Scope("prototype")
public class MyPrototypeBean {
// Class specific code
}

PrototypeWhat does a prototype-scoped bean object have to do with the Prototype Design Pattern? Share more in Prototype Design Patterns.

Summary:

The role of the singleton pattern consists of the following:

  1. Ensure globally unique instances: The singleton pattern ensures that only one instance of a class exists in the system, and that the same instance is obtained regardless of where it is instantiated. This prevents inconsistent or conflicting state between multiple objects, ensures consistent operation by all users, and helps manage global resources.
  2. Provides global access points: The singleton pattern provides a global access point, making it easy to access the instance from anywhere. This is useful in situations where frequent access to an object or shared resource is required, simplifying code logic and improving readability and maintainability.
  3. Conservation of system resources: Since the singleton pattern creates only one instance of an object, it can avoid the performance and memory consumption caused by repeated object creation. Especially in scenarios where the object is accessed frequently, the singleton pattern can effectively reduce the use of system resources.
  4. Controls the instantiation process of an object: The singleton pattern allows for tight control over the instantiation process of an object, ensuring that only one instance exists and that it is dynamically created or delayed at runtime to meet specific needs. This is useful when special handling or optimization of the object creation process is required.
  5. Avoid the misuse of global variables: The singleton pattern can encapsulate global state in a single object, avoiding the use of a large number of global variables and static methods, thus improving code maintainability and testability.

In short, the singleton pattern is useful when you need to ensure that only one instance of a class exists in the system and you need to provide a global access point. It can simplify system architecture, improve code reuse and maintainability, while saving system resources and improving system performance. But be careful, the question of whether the thread is safe or not.

Looking at Spring singleton scoped beans, you should know a little bit about it:

Rather than simply applying a fixed code framework to a project, design patterns are a way ofrigorous programming thinking, designed to provide experience and guidance in solving specific problems.

In the case of the single instance design pattern, which controls only one instance of a class and provides a global access point, mastering the application of this programming idea is the key to learning design patterns.

在这里插入图片描述

Soft Exam Intermediate - Software Designer unreserved preparation sharing

Heavy news for the second half of 2023 softball exams

Passing the soft exam but not receiving a physical certificate?

Computer Algorithm Design and Analysis (5th Edition)

Java Full Stack Learning Route, Learning Resources and Interview Questions in One Place

Soft exam certificates = title certificates?

What are design patterns?