[reading notes] analysis and practice of Android source code design mode (V) - factory mode mode

[reading notes] analysis and practice of Android source code design mode (1)
[reading notes] analysis and practice of Android source code design mode (2) - single case mode
[reading notes] analysis and practice of Android source code design mode (3) - builder mode
[reading notes] analysis and practice of Android source code design mode (IV) - prototype mode
[reading notes] analysis and practice of Android source code design mode (V) - factory mode mode

Definition

Define an interface for creating objects so that subclasses decide which class to instantiate.

Use scenario

Factory method patterns can be used wherever complex objects need to be generated. Complex objects are suitable for factory mode, and objects can be created with new without factory mode.

Simple implementation

/**
 * Abstract product class
 */
public abstract class Product {

    /**
     * Abstract methods of product classes, with specific products to implement
     */
    public abstract void method();
}

/**
 * Specific product A
 */
public class ProductA extends Product {
    @Override
    public void method() {
        System.out.print("Product A");
    }
}

/**
 * Specific product B
 */
public class ProductB extends Product {
    @Override
    public void method() {
        System.out.print("Product B");
    }
}

/**
 * Abstract factory class
 */
public abstract class Factory {

    public abstract ProductA createProductA();

    public abstract ProductB createProductB();

    public abstract <T extends Product> T createProduct(Class<T> cls) throws Exception;
}

/**
 * Specific factory
 */
public class ProductFactory extends Factory {

    @Override
    public ProductA createProductA() {
        return new ProductA();
    }

    @Override
    public ProductB createProductB() {
        return new ProductB();
    }

    @Override
    public <T extends Product> T createProduct(Class<T> cls) throws Exception {
        return  (T) Class.forName(cls.getName()).newInstance();
    }
}

public class Client {

    public static void main(String[] args){

        Factory factory = new ProductFactory();
        factory.createProductA().method();
        factory.createProductB().method();
        try {
            factory.createProduct(ProductA.class).method();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Tags: Android

Posted on Sat, 02 May 2020 06:48:12 -0700 by danieliser