Strategy pattern + factory pattern + Spring reflection

Strategy pattern + factory pattern + Spring reflection

1. Strategy mode

1 Overview

This mode defines some algorithms and encapsulates each algorithm so that they can be replaced with each other, and the change of the algorithm will not affect the customers who use the algorithm. The strategy mode belongs to the object behavior mode. It encapsulates the algorithm and puts The responsibility for using the algorithm is separated from the implementation of the algorithm and delegated to different objects to manage these algorithms

2. Structure

  • The main roles of the strategy pattern are as follows
    • Abstract strategy class (Strategy) class: This is an abstract role, usually has an interface or abstract class to achieve. This role gives all the interfaces required by the concrete strategy class
    • Concrete Strategy class: implements the interface defined by the abstract strategy, and provides specific algorithm implementation or behavior
    • Environment (Context) class: holds a reference to a strategy class, and finally calls it to the client

3. Case realization

Strategy case:

The three creatures are cats, dogs, and people

The three creatures correspond to eating different things

  • Strategy class

    public interface BiologicalStrategy {
        void show();
    }
    
  • CatConcrete Strategy

    public class CatStrategy implements BiologicalStrategy {
          
          
        @Override
        public void show() {
          
          
            System.out.println("吃猫粮");
        }
    }
    
  • Dog Concrete Strategy

    public class DogStrategy implements BiologicalStrategy {
          
          
        @Override
        public void show() {
          
          
            System.out.println("吃狗粮");
        }
    }
    
  • 人Concrete Strategy

    public class PersonStrategy implements BiologicalStrategy {
          
          
        @Override
        public void show() {
          
          
            System.out.println("吃饭");
        }
    }
    
  • Context class

    public class FoodContect {
          
          
        private BiologicalStrategy biologicalStrategy;
        public void biologicalStrategyShow() {
          
          
            biologicalStrategy.show();
        }
    }
    
  • main method

    public static void main(String[] args) {
          
          
        FoodContect catFood = new FoodContect(new CatStrategy());
        catFood.biologicalStrategyShow();
        System.out.println("====================");
        FoodContect dogFood = new FoodContect(new DogStrategy());
        dogFood.biologicalStrategyShow();
        System.out.println("====================");
        FoodContect personFood = new FoodContect(new PersonStrategy());
        personFood.biologicalStrategyShow();
    }
    

4. Summary

  • advantage
    • Free switching between strategy classes – Since the strategy classes all have the same interface, they can be switched freely
    • Easy to expand - adding a new strategy only needs to add a specific strategy class, basically no need to change the original code, in line with the "open and close principle"
    • Relatively avoid the use of multiple conditional selection statements (if-else || switch) in a specific scenario , fully embodying object-oriented thinking – but through the factory mode to reduce to a certain extent (if-else || switch)
  • shortcoming
    • The client must know all policy classes and decide for itself which policy class to use
    • The strategy pattern will result in more strategy classes, and the number of objects can be reduced to a certain extent by using the Flyweight pattern
  • scenes to be used
    • When a system needs to dynamically select one of several algorithms, each algorithm can be encapsulated into a strategy class
    • A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class, and each conditional branch can be moved into their respective strategy classes to replace these conditional statements
    • Each algorithm in the system is completely independent of each other, and when it is required to hide the implementation details of the specific algorithm from the client
    • When the system requires that the client using the algorithm should not know the data it operates, the strategy pattern can be used to hide the data structure related to the algorithm
    • Multiple classes only differ in their performance and behavior. You can use the strategy mode to dynamically select the specific behavior to be executed at runtime

2. Factory mode (three types: simple factory, factory method, abstract factory) -> advanced improvement strategy processing factory

In Java, everything is connected to objects, and these objects need to be created. If you directly new the object when you create it, it will be severely coupled to the object. If we want to replace the object, all new objects need to be modified, which obviously violates the Open-close principle of software design. If we use the factory to produce objects, we can only deal with the factory and completely decouple from the object. If we want to replace the object, we can directly replace the object in the factory. The purpose of object decoupling; therefore, the biggest advantage of the factory model is decoupling

1. Simple factory pattern (not part of 23 classic design patterns)

The simple factory pattern is not a design pattern, but a programming habit

①. Structure

  • Abstract product: defines the specification of the product and describes the main features and functions of the product
  • Concrete products: implement or integrate subclasses of abstract products
  • Specific factory: Provides a method to create a product, and the caller creates a product through the method

②. Realize

  • accomplish

    simple_factory code

    public class SimpleFactory {
          
          
        public FoodContect createFood(String type) {
          
          
            FoodContect foodContect = null;
            foodContect = new FoodContect(new CatStrategy());
            return foodContect;
        }
    }
    

    main method

    public static void main(String[] args) {
          
          
        SimpleFactory simpleFactory = new SimpleFactory();
        BiologicalStrategy cat = simpleFactory.createFood("cat");
        cat.show();
    }
    

    We can reduce a certain amount of coupling through the factory model, but here simple communism has created a new coupling, which violates the principle of opening and closing, but we only need to modify the code of the corresponding factory class to save other operations

③. Summary

  • advantage

    Encapsulates the process of creating an object, and you can directly obtain the object through parameters. Separate the creation of the object from the business logic layer, so that you can avoid modifying the customer code in the future. If you want to implement a new product, you can directly modify the factory class instead of in the source code modification, which reduces the possibility of client code modification and makes it easier to expand

  • shortcoming

    When adding new products, it is still necessary to modify the code of the factory class, which violates the principle of opening and closing

2. Static factory pattern (not part of 23 classic design patterns)

It just changes the method of the simple factory into a static method and does not introduce it in detail here.

3. Factory method pattern

  • The factory method model can perfectly solve the shortcomings of the above simple factory and static factory, and fully follow the principle of opening and closing
  • Define an interface for creating cash, let the subclass decide which product class object to instantiate. The factory method is a subclass that delays the instantiation of a product class to its factory

①. Structure

  • The main role of the factory method pattern:
    • Abstract Factory (abstract Factory): Provides an interface for creating products, and the caller creates products through her access to the factory method of the specific factory
    • The concrete factory (ConcreteFactory:) mainly implements the abstract method in the abstract factory to complete the creation of specific products
    • Abstract product (Product): defines the specification of the product and describes the main features and functions of the product
    • ConcreteProduct: implements the interface defined by the abstract product role, and is created by a specific factory, which corresponds to the specific factory one-to-one

②. Realize

  • factory method

    @NoArgsConstructor
    @AllArgsConstructor
    public class FactoryMethod {
          
          
        private FoodFactory foodFactory;
        public FoodFactory createFoodFactory() {
          
          
            return foodFactory;
        }
    }
    
  • abstract factory

    public interface FoodFactory {
          
          
        BiologicalStrategy createFood();
    }
    
  • specific factory

    // cat
    public class CatFactory implements FoodFactory{
          
          
        @Override
        public BiologicalStrategy createFood() {
          
          
            return new CatStrategy();
        }
    }
    
    
    // dog
    public class DogFactory implements FoodFactory {
          
          
        @Override
        public BiologicalStrategy createFood() {
          
          
            return new DogStrategy();
        }
    }
    
    
    // person
    public class PersonFactory implements FoodFactory {
          
          
        @Override
        public BiologicalStrategy createFood() {
          
          
            return new PersonStrategy();
        }
    }
    
  • main method (factory plus strategy)

    public static void main(String[] args) {
          
          
        FactoryMethod factoryMethod = new FactoryMethod(new CatFactory());
        FoodFactory foodFactory = factoryMethod.createFoodFactory();
        FoodContect foodContect = new FoodContect(foodFactory.createFood());
        foodContect.biologicalStrategyShow();
    }
    

③. Summary

  • advantage
    • Users only need to know the name of the specific factory to get the requested product, without knowing the specific creation process of the product
    • When adding new products to the system, it is only necessary to add specific product categories and corresponding specific tool categories, without any modification to the staff length, and to meet the principle of opening and closing
  • shortcoming
    • Every time a product is added, a specific product category and a corresponding specific factory category must be added, which increases the complexity of the system

4. Abstract factory pattern

The factory method model introduced earlier considers the production of one type of product, for example, a TV factory only produces TV sets

These factories only produce the same type of products, and the same type of products become the same level of products, that is to say: the factory method model only considers the production of products of the same level, but in real life, many factories are integrated factories that can produce multiple types of products

①. Concept

is an interface for accessing classes that create a set of related or interdependent objects

3. Misunderstanding -> The difference between factory and strategy

  • Use is different
  • The factory is a creational mode, and its function is to create objects;
  • Strategy is a behavioral pattern, its function is to let an object choose a behavior among many behaviors;
  • focus is different
  • A concern object is created
  • A behavior-focused wrapper
  • solve different problems
  • The factory mode is a creational design mode, which accepts instructions and creates instances that meet the requirements; it mainly solves the unified distribution of resources, completely independent of the creation of objects, so that the creation of objects has nothing to do with specific users. It is mainly used in multi-database selection, class library file loading, etc.
  • The strategy mode is to solve the switching and expansion of strategies. More concisely, it is to define strategy families and encapsulate them separately so that they can be replaced with each other. The strategy mode makes the change of the strategy independent of the client who uses the strategy.
  • The factory is equivalent to a black box, and the strategy is equivalent to a white box;

Guess you like

Origin blog.csdn.net/weixin_43194885/article/details/128795661