The factory method pattern for Java Design patterns

Source: Internet
Author: User
Tags export class

In the book "Java and Patterns" of Dr. Shanhong, this describes the factory method pattern:

The factory method pattern is the creation mode of the class, also known as the virtual Constructor mode or the Polymorphism factory (polymorphic Factory) pattern.

The factory method pattern is intended to define a factory interface that creates product objects, deferring actual creation to subclasses.

Then the factory method mode is used in what scenario, the following is an example of my understanding:

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 pay 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 export formats and 2 export structures, then the factory class requires 6 if else to create 6 different types. 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 is transformed into an abstract factory role that is only responsible for giving the interfaces that a specific factory subclass must implement, without touching which class should be instantiated in this detail.

This further abstraction allows the factory method model to allow the system to introduce new products without modifying the specific factory role, which undoubtedly makes the factory method model more advantageous than the simple factory model. The UML diagram is designed for the above requirements:

As can be seen, this system of using the factory method pattern involves the following roles:

  Abstract Factory (exportfactory) role : This role is at the heart of the factory method pattern, and any factory class that creates objects in the schema must implement this interface. In a real system, this role is often implemented using abstract classes.

  Specific Factory (Exporthtmlfactory, exportpdffactory) role : This role is the specific Java class that implements the abstract factory interface. The specific factory role contains logic that is closely related to the business and is invoked by the consumer to create an export class (for example: Exportstandardhtmlfile).

  abstract Export (exportfile) role : The superclass of the object created by the factory method pattern, which is the common parent or co-owned interface of all exported classes. In a real system, this role is often implemented using abstract classes.

  specific export (exportstandardhtmlfile, etc.) role : This role implements the interface declared by the abstract export (exportfile) role, and each object created by the factory method pattern is an instance of a specific export role.

Source Code

The first is the abstract factory role source code. It declares a factory method that requires all specific factory roles to implement this factory method. The parameter type represents the structure of the exported format, such as: Export HTML format There are two kinds of structure, one is the standard structure, and the other is the structure of financial needs.

 Public Interface exportfactory {
Public Exportfile Factory (String type);
}

Specific factory role class source code:

 Public classExporthtmlfactoryImplementsexportfactory{

@Override
PublicExportfile Factory (String type) {
//TODO auto-generated Method Stub
if("Standard". Equals (Type)) {

return NewExportstandardhtmlfile ();

}Else if("Financial". Equals (Type)) {

return NewExportfinancialhtmlfile ();

}Else{
Throw NewRuntimeException ("no object Found");
}
}

}
 Public classExportpdffactoryImplementsexportfactory {

@Override
PublicExportfile Factory (String type) {
//TODO auto-generated Method Stub
if("Standard". Equals (Type)) {

return NewExportstandardpdffile ();

}Else if("Financial". Equals (Type)) {

return NewExportfinancialpdffile ();

}Else{
Throw NewRuntimeException ("no object Found");
}
}

}

Abstract export Role class source code:

 Public Interface Exportfile {
Public boolean export (String data);
}

Specific export of the role class source code, typically this class will have complex business logic.

 Public class Implements exportfile{

@Override
Public boolean export (String data) {
// TODO auto-generated Method Stub
/**
* Business logic
*/
SYSTEM.OUT.PRINTLN ("Export Financial HTML file");
return true;
}

}
 Public class Implements exportfile{

@Override
Public boolean export (String data) {
// TODO auto-generated Method Stub
/**
* Business logic
*/
SYSTEM.OUT.PRINTLN ("Export financial PDF file");
return true;
}

}
 Public class 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 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 role class source code:

 Public class Test {

/**
@param args
*/
Public Static void Main (string[] args) {
// TODO auto-generated Method Stub
String data = "";
New Exporthtmlfactory ();
Exportfile EF = exportfactory.factory ("financial");
Ef.export (data);
}

}
activity sequence diagram for factory method mode

The client creates the Exporthtmlfactory object, when the static type of the variable that the client holds is exportfactory, and the actual type is exporthtmlfactory. The client then calls the Exporthtmlfactory object's Factory Method factory (), which then calls the Exportfinancialhtmlfile's constructor to create the exported object.

Factory method mode and simple Factory mode

The structural differences between the factory method pattern and the simple factory model are obvious. The core of the factory approach pattern is an abstract factory class, while the simple factory model places the core on a specific class.
Factory methods can become much like simple Factory mode after degradation. Imagine merging abstract factory classes into specific factory classes if you are very sure that a system requires only one specific factory class. Since there is only one specific factory class, it may be useful to change the factory method to a static method, and the simple Factory mode is obtained.

If the system needs to add a new export type, all that is needed is to add an export class to the system and the corresponding factory class. There is no need to modify the client, nor is it necessary to modify the abstract factory role or other existing specific factory roles. This system fully supports the open-close principle for adding new types of exports.
  

End

An application system is developed by multiple people, and the exported function is implemented by you, but the user (the person who called the method) may be someone else. At this point you should be flexible enough to minimize the coupling between the two, and when you modify or add a new feature, the user does not need to modify it anywhere. If your design is not flexible enough, you will not be able to face the changing needs of customers. Perhaps a minimal requirement change will change your code structure and cause other people who use the interface you provide to modify their code. Take one place and move the whole body, which makes the system difficult to maintain in the future.

  






The factory method pattern for Java Design patterns

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.