Spring-boot读书笔记一Factory Class

Factory Class (Design Pattern)
Definition: A class that creates and returns instances of other classes without exposing the instantiation logic to the client.

Purpose

  • Object Creation: Centralizes object creation logic
  • Abstraction: Hides complex instantiation details
  • Flexibility: Easy to change implementation without affecting client code

Types of Factory Patterns

  • Simple Factory: Single method creates objects based on parameters
  • Factory Method: Subclasses decide which class to instantiate
  • Abstract Factory: Creates families of related objects

Example - Simple Factory

public class DatabaseFactory {
    public static Database createDatabase(String type) {
        switch(type) {
            case "mysql": return new MySQLDatabase();
            case "postgres": return new PostgreSQLDatabase();
            default: throw new IllegalArgumentException("Unknown type");
        }
    }
}

Factory in Code Context
In your Spring Security configuration, you're not using a traditional factory class, but Spring's @Bean annotation acts as a factory method:


@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(); // Factory method
}

This method:
Creates BCryptPasswordEncoder instances
Managed by Spring container
Returns the same instance when requested (singleton by default)

Benefits

  • Loose coupling: Client doesn't know concrete classes
  • Easy testing: Can return mock objects
  • Configuration centralized: All creation logic in one place
  • Runtime decisions: Can choose implementation at runtime

Factory classes promote the "Don't call us, we'll call you" principle by letting the factory handle object creation complexity.

posted @ 2026-01-08 11:58  kkbln  阅读(8)  评论(0)    收藏  举报