Design pattern - factory pattern (3)

Factory pattern (3)

Definition: Define an interface for creating objects and let subclasses decide which class to instantiate. Factory methods defer the instantiation of a class to its subclasses.

  • abstract product class
  • specific product category
  • abstract factory class

1. Abstract factory class

public abstract class Computerfactorys {

    public abstract <T extends Computer> T createComputer(Class<T> clz);

}

2. Specific factory class

public class GDComputerfactory extends Computerfactorys {
    
    

    @Override
    public <T extends Computer> T createComputer(Class<T> clz) {
        Computer computer = null;
        String classname = clz.getName();
        try {
        //通过反射来生产不同厂家的电脑
            computer = (Computer) Class.forName(classname).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) computer;
    }
}

3. Abstract product class and concrete product class
These two classes are the same as the simple factory pattern.

4. Easy to use

public class Client {
    public static void main(String[] args) {

        Computerfactorys computerfactory = new GDComputerfactory();
        LenovoComputer lenovoComputer = computerfactory.createComputer(LenovoComputer.class);
        lenovoComputer.start();
    }
}

Summarize

  • Simple factory mode: The factory class contains the necessary logical judgments, and dynamically instantiates related classes according to different conditions. This removes the dependence on specific products; but at the same time it also brings a problem; if we need to add a new product, we need to add a case judgment in the factory class to instantiate the class, which violates the open and closed The principles are also open to modification. The factory pattern does not violate this principle. There is no need to modify the factory class, just create the product directly.

Guess you like

Origin blog.csdn.net/u013290250/article/details/82384425