Factory method mode of design mode popularization

Keywords: Android

This article is a note after reading "analysis and practice of Android source code design pattern"

Definition

Define an interface for creating objects, and let the subclass decide the instantiation category.

Usage scenarios

When some complex objects need to be generated, the specific scenarios still need to be weighed by developers.

Simple example:

public abstract class Computer {
    public abstract void complete();
}

public class MacBookComputer extends Computer{
    @Override
    public void complete() {
        System.out.println("Assemble MacBook");
    }
}

public abstract class Factory {
    public abstract Computer buildComputer();
}

public class MacBookFactory extends Factory{
    @Override
    public Computer buildComputer() {
        return new MacBookComputer();
    }
}

public class Client {
    public static void main(String[] args) {
        Factory factory = new MacBookFactory();
        Computer computer = factory.buildComputer();
        computer.complete();
    }
}

Factories using reflection:

public abstract class Factory {
    public abstract <T extends Computer> Computer buildComputer(Class<T> clazz);
}

public class MacBookFactory extends Factory{

    @Override
    public <T extends Computer> Computer buildComputer(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}


public class Client {
    public static void main(String[] args) {
        Factory factory = new MacBookFactory();
        Computer computer = factory.buildComputer(MacBookComputer.class);
        computer.complete();
    }
}

The book suggests that file storage in Android development can be implemented in factory mode, which is left to our readers.
Advantage

The book only uses code to specify the advantages. Personal understanding is to avoid the implementation details, convenient type switching, and personal ignorance.

shortcoming

New products need to create new product classes, which leads to the complexity of class structure

Posted by anita999 on Tue, 31 Dec 2019 14:04:20 -0800