This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

Maybe a lot of people learn design patterns first and then maybe last. This is a relatively simple pattern that communicates the idea of encapsulation and isolation to developers. A factory is a more advanced way to instantiate a class (as opposed to new Object()), and this is one of the suggestions for creating classes mentioned at the beginning of Effective Java. So again, what are the benefits of the factory model:

  • Creation and use are isolated, and objects are created without concern for their internal implementation
  • After the behavior is abstracted, including multiple classes with similar functions can save a lot of repetitive code
  • The business needs to change the logic without having to drastically change all the implementations

Here are some examples:

The figure contains two abstract classes: Factory and Product. The Factory method contains the creation and registration of the Product, and the create() method is the method of instantiating the open Product object. The specific implementation is as follows:

public abstract class Factory {
    public final Product create(String owner) {
        Product p = createProduct(owner);
        registerProduct(p);
        return p;
    }
    
    protected abstract Product createProduct(String owner);
    protected abstract void registerProduct(Product product);
}

public abstract class Product {
    public abstract void use(a);
}
Copy the code

Subclasses must implement the createProduct method to use create(), which is set to final. Subclasses can directly use and instantiate Product. Now it is the instance creation of IDCard. If the business needs an object such as TVProduct to be created, it can directly implement the abstract method without modifying any abstract method.

In retrospect, this is very similar to the template method pattern in that it abstracts behavior and avoids duplicate code. Even among the 23 so called design patterns, many of them are very similar after learning about them, only to change their names. There are subtle differences, but one thing that remains the same is that the behavior is abstracted, and by giving subclasses the details, you save a lot of boilerplate code, which is then more maintainable.