Factory method schema definition

The Fatory Method Pattern defines an interface for creating an object, but lets the class implementing the interface decide which class to instantiate. Factory methods defer class instantiation to subclasses. Belongs to the creation pattern.

Factory method pattern trial scenario

Creating objects requires a lot of repetitive code

The client (application layer) does not depend on the details of how the product class instance is created, implemented, etc. A class subclasses which objects are created.

Advantages of the factory method pattern

The user cares only about the factory of the desired product, not about the creation details.

The addition of new products conforms to the open and close principle and improves the scalability of the system.

Disadvantages of the factory method pattern

It is easy to have too many classes, which increases the complexity of the code structure.

Increases the abstractness and difficulty of understanding the system.

Differences between the simple factory pattern and the factory method pattern

Simple factories are factories of products, and factory methods are factories of factories.

1. Class Diagram:

Ii. Products (Courses)

1. ICouse: Course interface

public interface ICouse {
    void record();
}
Copy the code

PythonCouse: Python course implementation class

Public class implements ICouse {@override public void record() {system.out.println ("Python "); }}Copy the code

3. JavaCouse: Java course implementation class

Public class JavaCouse implements ICouse {@override public void record() {system.out.println (); }}Copy the code

Iii. Product Factory (Course)

1, ICourseFactory: course factory interface

public interface ICourseFactory {
    ICouse create();
}

Copy the code

PythonCourseFactory: A Python course factory

public class PythonCourseFactory implements ICourseFactory { @Override public ICouse create() { return new PythonCouse(); }}Copy the code

3, JavaCourseFactory: Factory implementation class, Java course factory

public class JavaCourseFactory implements ICourseFactory { @Override public ICouse create() { return new JavaCouse(); }}Copy the code

Iv. Test class:

public class Test { public static void main(String[] args) { JavaCourseFactory javaCourseFactory = new JavaCourseFactory(); javaCourseFactory.create().record(); PythonCourseFactory pythonCourseFactory = new PythonCourseFactory(); pythonCourseFactory.create().record(); }}Copy the code