Factory method Mode (Virtual constructor/polymorphic Factory)
The factory method pattern is the creation mode of the class, also known as virtual Construction sub-mode (Vsan Constructor) or polymorphism Factory mode (polymorphic Factory).
The factory method pattern is intended to define a factory interface that creates product objects, deferring actual creation to subclasses.
So what is the factory method model used for? Here's an example:
Believe that many people have done import and export functions, take the export function. There is a requirement: XX system needs to support the export of payroll in the database, and support a variety of formats such as: Html,csv,pdf, and so on, each format export structure is different, such as financial and other people on the export of payroll HTML format requirements may be different, Because finance may require a specific format for easy accounting or other purposes.
If you use the Simple factory model, the factory class must be too bloated. Because the simple factory model has only one factory class, it needs to handle all the created logic. If the above requirements temporarily support only 3 of the export format and 2 of the exported structure, then the factory class requires 6 if else to create a different type in 6. If demand increases in the future, the consequences will be dire.
This is where the factory approach model is needed to handle the above requirements. In factory method mode, the core factory class is no longer responsible for the creation of all objects, but rather the creation of the work is given to subclasses to do. This core class has been transformed into an abstract factory role that is only responsible for giving the interfaces that a specific factory subclass must implement, without touching which kind of detail should be instantiated.
Java design mode-factory method mode (Virtual constructor/polymorphic Factory)