Design Pattern 2 - Factory Method Pattern

Factory method pattern:

Definition: Define an interface for creating objects and let subclasses decide which class to instantiate. A factory method delays the instantiation of a class to its subclasses.

Class Diagram:


The abstract product class Product is responsible for defining the commonality of products and implementing the most abstract definition of things. Creator creates classes for abstraction, that is, abstract factories. How to create product classes is done by the concrete implementation factory ConcreteCreator.

Generic code:

Abstract product class:

public abstract class Product {
    // public method of product class
    public void method1(){
        //Business logic processing
    }
    // abstract method
    public abstract void method2();
}

Specific product categories:

public class ConcreteProduct1 extends Product {
    public void method2() {
        //Business logic processing
    }
}
public class ConcreteProduct2 extends Product {
    public void method2() {
        //Business logic processing
    }
}

Abstract factory class:

public abstract class Creator {
    /*
    * Create a product object, whose input parameter type can be set from * line, usually String, Enum, Class, etc., or it can be empty
    */
    public abstract <T extends Product> T createProduct(Class<T> c);
}

Specific factory class:

public class ConcreteCreator extends Creator {
    public <T extends Product> T createProduct(Class<T> c){
        Product product=null;
        try {
            product = (Product)Class.forName(c.getName()).newInstance();
        } catch (Exception e) {
            // exception handling
        }
        return (T)product;
    }
}

Scene class:

public class Client {
    public static void main(String[] args) {
        Creator creator = new ConcreteCreator();
        Product product = creator.createProduct(ConcreteProduct1.class);
        /*
        * Business logic processing
        */
    }
}

Precautions:

As a class creation pattern, the factory method pattern can be used anywhere complex objects need to be generated. One thing to note is that complex objects are suitable for using the factory pattern, while simple objects, especially those that can be created only through new, do not need to use the factory pattern. If you use the factory pattern, you need to introduce a factory class, which will increase the complexity of the system.

An extension of the factory pattern:

(1) Reduced to a simple factory pattern: Simple factory pattern

If a module only needs a factory class, there is no need to generate it, just use the static method directly.


2. Upgrade to multiple factory classes


3. Alternative singleton pattern


4. Delayed initialization



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325440488&siteId=291194637