Design Patterns-factory method patterns

Source: Internet
Author: User
Tags export class

Design Patterns-factory method patterns
Dr. Yan Hong's book "JAVA and patterns" describes the factory method patterns in this way:
  The Factory method mode is the class creation mode, also known as the Virtual Constructor mode or the Polymorphic Factory mode.
The purpose of the factory method mode is to define a factory interface for creating product objects and postpone the actual creation to the subclass.

SoFactory method modeIn what scenarios is it used? The following is an example of my understanding:
I believe that many people have done the Import and Export function, taking the export function as an example. The XX system needs to support the export of employee salaries in the database and multiple formats such as HTML, CSV, and PDF. The exported structure of each format is different, for example: finance and others may have different requirements on the HTML format for salary export, because finance may need 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 mode has only one factory class, it needs to process all the created logic. If the above requirements only support three export formats and two export structures, then the factory class requires six if else to create six different types. If demand increases in the future, the consequences will be unimaginable.

At this time, the factory method mode is required to deal with the above requirements. In the factory method mode, the core factory class is no longer responsible for the creation of all objects, but the specific creation work is handed over to the subclass. This core class changes and becomes an abstract factory role. It is only responsible for providing the interface that must be implemented by the specific factory subclass without touching the details of which class should be instantiated.
This further abstract result allows the factory method mode to allow the system to introduce new products without modifying the specific factory role, this feature undoubtedly makes the factory method model more advantageous than the simple factory model. The following is a UML diagram for the above requirements:


It can be seen that the system using the factory method model involves the following roles:
 Abstract Factory role:This role is at the core of the factory method mode. Any factory class that creates an object in the mode must implement this interface. In actual systems, this role is often implemented using abstract classes.

  Specific Factory (ExportHtmlFactory, exportpdffacloud) roles:The role is a specific JAVA class that implements the abstract factory interface. The specific factory role contains the logic closely related to the business and is called by the user to create an export class (for example, ExportStandardHtmlFile ).

  Abstract Export (ExportFile) role:The superclass of the object created in the factory method mode, that is, the common parent class or interfaces of all export classes. In actual systems, this role is often implemented using abstract classes.

  Specific export roles (such as ExportStandardHtmlFile:This role implements the interface declared by the abstract Export (ExportFile) role. Every object created in the factory method mode is an instance of a specific export role.
Source code
The first is to abstract the source code of the factory role. It declares a factory method that requires all specific factory roles to implement this factory method. The type parameter indicates the structure of the exported format. For example, the exported HTML format has two structures: standard structure and financial structure.

public interface ExportFactory {    public ExportFile factory(String type);}
Specific factory corner class source code:
Public class ExportHtmlFactory implements ExportFactory {@ Override public ExportFile factory (String type) {// TODO Auto-generated method stub if ("standard ". equals (type) {return new ExportStandardHtmlFile ();} else if ("financial ". equals (type) {return new exportexternalhtmlfile () ;}else {throw new RuntimeException ("no object found ");}}}


Public class ExportPdfFactory implements ExportFactory {@ Override public ExportFile factory (String type) {// TODO Auto-generated method stub if ("standard ". equals (type) {return new ExportStandardPdfFile ();} else if ("financial ". equals (type) {return new exportexternalpdffile () ;}else {throw new RuntimeException ("no object found ");}}}

Abstract export the source code of the role class:
public interface ExportFile {    public boolean export(String data);}
Export the source code of the role class. Generally, this class has complicated business logic.
Public class ExportFinancialHtmlFile implements ExportFile {@ Override public boolean export (String data) {// TODO Auto-generated method stub/*** business logic */System. out. println ("Export Finance HTML file"); return true ;}}

Public class exportpolicalpdffile implements ExportFile {@ Override public boolean export (String data) {// TODO Auto-generated method stub/*** business logic */System. out. println ("Export Finance PDF file"); return true ;}}

Public class ExportStandardHtmlFile implements ExportFile {@ Override public boolean export (String data) {// TODO Auto-generated method stub/*** business logic */System. out. println ("export standard HTML file"); return true ;}}

Public class ExportStandardPdfFile implements ExportFile {@ Override public boolean export (String data) {// TODO Auto-generated method stub/*** business logic */System. out. println ("Export Standard PDF file"); return true ;}}

Client Angle class source code:
public class Test {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        String data = "";        ExportFactory exportFactory = new ExportHtmlFactory();        ExportFile ef = exportFactory.factory("financial");        ef.export(data);    }}

Activity sequence diagram of factory method mode

When the client creates an ExportHtmlFactory object, the static type of the variables held by the client is ExportFactory, and the actual type is ExportHtmlFactory. Then the client calls the factory method factory () of the ExportHtmlFactory object, and the latter calls the constructor of exportexternalhtmlfile to create the export object.

Factory method mode and simple factory Mode
The factory method mode and the simple factory mode have different structures. The core of the factory method mode is an abstract factory class, while the simple factory mode places the core on a specific class.
After the factory method model degrades, it can become much like a simple factory model. Imagine that if a system requires only one specific factory class, you may wish to merge the abstract factory class into a specific factory class. Since there is only one specific factory type, you may wish to change the factory method to a static method. At this time, a simple factory mode is obtained.

If the system needs to add a new export type, you need to add this export class and the corresponding factory class to the system. There is no need to modify the client, or modify the abstract factory role or other existing factory roles. For new export types, this system fully supports the "open-close principle ".
  
End
An application system is developed by many people. The export function is implemented by you, but the user (who calls this method) may be others. At this time, you should be flexible enough to minimize the coupling between the two. When you modify or add a new function, users do not need to modify anything. If your design is not flexible enough, you will not be able to face the changing needs of customers. A minor requirement change may change your code structure and cause others who use the interfaces you provide to modify their code. This makes it difficult to maintain the system in the future.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.