Factory method Mode

Source: Internet
Author: User

1. Pattern definition

Problem Description:

Usually there are some conventions in the exported data format, such as export to text format, database backup form, Excel format, XML format.
For the business function object that implements the data export, it needs to create the concrete implementation object of the EXPORTFILEAPI, but it knows the Exportfileapi interface, but does not know its concrete implementation, what should do?

Definition of the factory method pattern:

Define an interface for creating an object, let subclasses decide which class to instantiate, and Factory delay the implementation of a class to its subclasses.

2. UML diagram


Product: An interface that defines the objects created by the factory method, that is, the interface that implements the objects that need to be used
The implementation object of Concreteproduct:product
Creator: Declares a factory method, a factory method typically returns an instance object of a product class, and many are abstract methods
Concretecreator: Overrides the factory method that implements the creator definition, returning the specific product instance

Specific code:

/** * Interface for exported file objects * / Public  interface exportfileapi {    /** * Export content becomes a file * @param data schematic: required to be saved * @return Whether the export was successful */     Public Boolean Export(String data);}/** * Export the object as a database backup file * / Public  class exportdb implements Exportfileapi{     Public Boolean Export(String data) {//Simply indicate that you need to manipulate the database and files hereSystem.out.println ("Export Data"+data+"To database backup file");return true; }}/** * Objects exported to text file format * / Public  class exporttxtfile implements Exportfileapi{     Public Boolean Export(String data) {//Simply indicate that you need to manipulate the files hereSystem.out.println ("Export Data"+data+"To text file");return true; }}/** * The business function object that implements the exported data * / Public Abstract  class exportoperate {    /** * Export file * @param data needs to be saved * @return whether to export the file successfully */     Public Boolean Export(String data) {//Use factory methodExportfileapi API = FactoryMethod ();returnApi.export (data); }/** * Factory method, create an interface object for the exported file object * @return The interface object of the exported file object * /    protected AbstractExportfileapiFactoryMethod();}/** * Specific creator implementation object for creating an object that is exported as a database backup file * / Public  class exportdboperate extends exportoperate{    protectedExportfileapiFactoryMethod() {//Create an object that is exported as a database backup file        return NewExportdb (); }}/** * Specific creator implementation object for creating objects exported to a text file format */ Public  class exporttxtfileoperate extends exportoperate{    protectedExportfileapiFactoryMethod() {//Create an object that is exported as a text file format        return NewExporttxtfile (); }} Public  class Client {     Public Static void Main(string[] args) {//Create creator objects that need to be usedExportoperate operate =NewExportdboperate ();//function method for invoking output dataOperate.export ("test Data"); }}
3. Grinding design mode

The function of the factory method pattern is mainly that the parent class does not know the concrete implementation of the situation, the completion of its own function calls, and the specific implementation let the subclass to do.

The nature of factory methods: Delay to subclass to select implementations, better maintainability and scalability

The factory method is generally not exposed to the client

IOC and DI

IOC Inversion of control inversion
DI Dependency Injection Dependency Injection
Dependency injection and control inversion are different descriptions of the same thing
Dependency Injection: From an application perspective, the application relies on the container to create and inject the external resources it needs;
Control reversal: From the container's perspective, the container controls the application, which is injected by the container into the program's external resources as needed.
1. Who is the participant: one is a Java object, the other is a Ioc/di container, and the other is an external resource for an object
2. Who depends on who: a Java object that relies on the Ioc/di container
3. Why you need to rely on: objects need to ioc/di containers to provide the external resources required by the object
4. Who injects: Ioc/di container injects an external resource
5. What to inject: the external resources required to inject an object
6. Who controls who: Ioc/di container control objects
7. Controlling What: Controlling the creation of object instances

Parametric chemical Plant method values are: By passing parameters to factory methods, the factory method creates different product objects depending on the parameters.

/** * The business function object that implements the exported data * / Public  class exportoperate {    /** * Export file * @param Type user selected export type * @param data needs to be saved * @return Whether the file was successfully exported */     Public Boolean Export(intType,string data) {//Use factory methodExportfileapi API = FactoryMethod (type);returnApi.export (data); }/** * Factory method, create an interface object for the exported file object * @param Type user selected export type * @return The exported file object's interface object */    protectedExportfileapiFactoryMethod(intType) {EXPORTFILEAPI API =NULL;//Select which export file object to create according to the type        if(type==1) {API =NewExporttxtfile (); }Else if(type==2) {API =NewExportdb (); }returnApi }} Public  class Client {     Public Static void Main(string[] args) {//// Create creator objects that need to be used//Exportoperate operate = new Exportoperate ();///// Call the function method of the output data, incoming select the parameters of the type everywhere//Operate.export (1, "test Data");        //Create creator objects that need to be usedExportoperate operate =NewExportOperate2 ();//Change incoming parameters below to test parameter chemical plant methodOperate.export (1,"Test1"); Operate.export (2,"Test2"); Operate.export (3,"Test3"); }}//Extension very easy/** * Extended Exportoperate object, join can export XML file */ Public  class ExportOperate2 extends exportoperate{    /** * Overrides the parent class of the factory method, creating an interface object for the exported file object * @param type of the user-selected export type * @return The exported file object's interface object */    protectedExportfileapiFactoryMethod(intType) {EXPORTFILEAPI API =NULL;//Can be fully covered, or you can choose the coverage of your own interest,        //Here you just want to add your own new implementation, other whatever        if(type==3) {API =NewExportXML (); }Else{//Other or let the parent class implementAPI =Super. FactoryMethod (type); }returnApi }}

Factory method Mode

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.