Design Pattern 07-factory method (creation type)

Source: Internet
Author: User
1. Scenario Problems

Application Framework for data export

Consider such a practical application to implement an application framework for data export to allow customers to select a data export method (there may be a Database Export method or a text export method ), and export the data.

1.1 What is the basic knowledge of the Framework 1.1.1?

The framework is a semi-finished software that can complete certain functions.

1.1.2 what can the Framework do?

Can complete certain functions and speed up Program Development

Give us a sophisticated program architecture

1.1.3 understanding of the framework

Based on the framework development, things are still those things, but they only depend on who is doing the problem.

Based on framework development, you can not do what the framework does, but you should understand what the framework is doing and how the framework implements its functions.

1.1.4 relationship between framework and Design Model

The design pattern is more abstract than the framework

The design pattern is an architectural element smaller than the framework.

The framework is more special than the design model.

1.2 problem:

Analysis of the above application framework, no matter what type of export format the user chooses, the final export is a file, and the system does not know what type of file to export, so there should be an interface, to describe the last generated object and operate the output file.

The sample code is as follows:

 

Package demo05.factorymethod. example1;/*** interface for exporting file objects */public interface exportfileapi {/*** export content into a file ** @ Param data: data to be saved * @ return: whether the data is exported successfully */Public Boolean Export (string data );}

For the function of exporting data business objects, it should create the corresponding exportfileapi implementation objects as needed, because the implementation of specific exportfileapis is related to specific businesses, however, for the business function objects that implement the exported data, it does not know which exportfileapi object to create or how to create it..

2. Solve the Problem 2.1 use the factory method mode to solve the problem

Factory method mode definition: defines an interface for creating objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.

The solution to the factory method model is very interesting, that is, the solution is not to solve the problem, and the solution is to do nothing.

Structure of factory method mode

Interface of the actually used object of Product

Implementation object of the specific interface of concreteproduct

Creator creator, declaring the factory Method

Concretecreator: Specifies the object of the Creator, overwrites the factory method defined by the Creator, and returns the specific product instance.

2.2 Sample Code of factory method mode

 

Package demo05.factorymethod. example2;/*** interface of the object created by the factory Method */public interface product {// method of defining the product}

Package demo05.factorymethod. example2;/*** specific product object */public class concreteproduct implements product {// method to meet product requirements}

Package demo05.factorymethod. example2;/*** producer, declare factory Method */public abstract class creator {/*** create factory method of product ** @ return product object */protected abstract product factorymethod (); /*** indicates a method to implement certain functions */Public void someoperation () {// usually in the implementation of these methods, you need to call the factory method to obtain the product object product Product = factorymethod ();}}

Package demo05.factorymethod. example2;/*** specific creator implementation object */public class concretecreator extends creator {public product factorymethod () {// redefine the factory method, return a specific product object return New concreteproduct ();}}
2.3 if you use the factory method to solve problems in the scenario, you must first match the product and creator.

Implement the sample program structure using the factory method mode


The code is implemented as follows:

 

Package demo05.factorymethod. example3;/*** interface for exporting file objects */public interface exportfileapi {/*** export content into a file ** @ Param data: data to be saved * @ return: whether the data is exported successfully */Public Boolean Export (string data );}
Package demo05.factorymethod. example3;/*** export to an object in the text file format */public class exporttxtfile implements exportfileapi {public Boolean Export (string data) {// a simple illustration, the file system needs to be operated here. out. println ("export data" + Data + "to text file"); Return true ;}}

Package demo05.factorymethod. example3;/*** export to an object in the form of a database backup file */public class exportdb implements exportfileapi {public Boolean Export (string data) {// briefly, here you need to operate the database and file system. out. println ("export data" + Data + "Back up database file"); Return true ;}}

Package demo05.factorymethod. example3; /*** business function object for data export */public abstract class exportoperate {/***** export file ** @ Param data * data to be saved * @ return whether data is successfully exported file */Public Boolean Export (string data) {// use the factory method exportfileapi API = factorymethod (); Return API. export (data);}/*** factory method, create the exported file object interface object ** @ return interface object of the exported file object */protected abstract exportfileapi factorymethod ();}

Package demo05.factorymethod. example3;/*** specific creator implementation object to create and export an object in text file format */public class exporttxtfileoperate extends exportoperate {protected exportfileapi factorymethod () {// create an object exported as a text file format return New exporttxtfile ();}}

Package demo05.factorymethod. example3; public class client {public static void main (string [] ARGs) {// create the Creator object exportoperate operate = new exportdboperate () to be used (); // call the function operate of the output data. export ("Test Data ");}}

3. Mode description 3.1 functions of the factory method mode

The main function of the factory method mode is to allow the parent class to call its own functions without knowing the specific implementation, and the specific implementation delay is implemented by the subclass.

3.2 implement as an abstract class

In the implementation of factory methods, the parent class is usually an abstract class that contains the abstract methods for creating objects. These abstract methods are factory methods.

Here, we need to pay attention to a problem. When implementing these abstract methods, subclasses do not actually implement specific functions by subclasses, but select them in subclass methods, select a specific product implementation object.

3.3 implement as a specific class

You can also implement the parent class into a specific class. In this case, a specific subclass is required to determine how to create the objects required by the parent class. In this case, the factory method also provides hooks for sub-classes. The factory method allows subclass objects to overwrite the implementation of parent classes to provide better flexibility.

3.4 factory method parameters and responses

Generally, the interface object of the created object is returned. Of course, it can be an abstract class or an instance of a specific class.

3.5 who will use the factory method to create objects

In the factory mode method, other methods in the Creator are the objects created using the factory method, but the factory method is generally not provided for external use by the creator.

3.5.1 client creator object usage

 

Package demo05.factorymethod. example4;/*** when the client uses the Creator object, the basic implementation structure of the Creator */public abstract class creator {/*** factory method, generally, the product object created by ** @ return */protected abstract product factorymethod ();/*** is not provided to external users, the client generally uses the methods provided by creator to complete the required functions */Public void someoperation () {// here use the factory method product P = factorymethod ();}}

3.5.2 objects created by the client using creator

 

Package demo05.factorymethod. example5;/*** when the client uses creator to create the objects required by the client, the basic implementation structure of the Creator */public abstract class creator {/*** factory method, generally, the product object created by ** @ return is not an external part. It is generally a part of another product object */protected abstract product1 factorymethod1 ();/*** factory method, generally, the product object created by ** @ return is not an external part. It is generally a part of another product object */protected abstract product2 factorymethod2 (); /*** create the objects required by the client. The client mainly uses the product objects to complete the required functions ** @ return the objects required by the client */Public Product createproduct () {// use the factory method here to obtain the part object product1 p1 = factorymethod1 (); product2 P2 = factorymethod2 (); // The object created by the factory method is the product P = new concreteproduct (); p. setproduct1 (P1); p. setproduct2 (P2); Return P ;}}

3.6 The Call Sequence of the factory method mode is as follows 3.6.1 The following is called using the Creator object:

 

 

3.6.2 call the objects created by using creator is as follows:

 

4. Factory method mode and IOC/di

IOC control Inversion

Di dependency Injection

4.1 understand concepts 4.1.1 who are involved?

One is an object, the other is an IOC/di container, and the other is an external resource of an object.

Here, a pair of related objects refer to any Java object.

4.1.2 who depends on whom?

Of course, an object depends on the IOC/di container.

4.1.3 why is dependency required?

The IOC/di container is required for the object to provide the external resources required by the object.

4.1.4 who injected who?

It is obvious that the IOC/di container injects an object.

4.1.5 what is injection?
External resources required to inject an object

4.1.6 who controls who?
Of course, it is the container of IOC/di to control objects.

4.1.7 what control?

It mainly controls the creation of object instances.

4.1.8 why is it "reverse "?
If C is required in a, the C object is directly created. In this way, a actively obtains the required resource file class C, which is called forward. So what is reverse? That is to say, a no longer actively acquires Class C. Instead, wait passively, wait for IOC/di to obtain a class C instance, and then inject it into Class A in reverse.

4.1.9 is dependency injection the same concept as control reversal?

Dependency injection: The application depends on the container to create and inject the external resources required by the application;

Control reversal: The container controls the application, and the container reversely injects the required external resources into the application.

4.2 relationship between factory method mode and IOC/di

As mentioned above, with IOC/di, applications no longer take the initiative, but passively wait for containers to inject resources. When writing code, once external resources are used, a window will be opened to allow containers to inject in, that is, a channel to inject used by containers, of course, this is not the focus. Let's use setter injection as an example. The sample code using IOC/DI is as follows:

 

 

Package demo05.factorymethod. example6; public class A {/*** waiting for injection */private C = NULL; /*** Method for injecting resource C ** @ Param C * injected resource */Public void SETC (C) {This. C = C;} public void T1 () {// Class C needs to be used here, but it does not allow the user to create C. What should I do? // Injection from the outside is required anyway, which is more worry-free. // you can directly use C. TC ();} instead of getting C ();}}

package demo05.factorymethod.example6;public interface C {public void tc();}

The factory method mode implements the above functions. The sample code is as follows:

 

Package demo05.factorymethod. example6; public abstract class A1 {/*** factory method, create C1, similar to the way to inject data from subclass ** @ return C1 object instance */protected abstract C1 createc1 (); Public void T1 () {// C1 class is required here, but I don't know which one is used, so I don't take the initiative to create C1. What should I do? // It will be implemented in the subclass anyway, which is more worry-free. You don't have to worry about how to get C1 here. Just use createc1 (). TC ();}}
Package demo05.factorymethod. example6; public class A2 extends A1 {protected C1 createc1 () {// select the actual implementation and create the object return New C2 ();}}

package demo05.factorymethod.example6;public interface C1 {public void tc();}

package demo05.factorymethod.example6;public class C2 implements C1 {public void tc() {// TODO Auto-generated method stub}}

5. Balanced class hierarchy 5.1 the meaning of a balanced class hierarchy:

If there are two class hierarchies, each class in one class hierarchy has a corresponding class structure in the other class layer, it is called a parallel class hierarchy.

An example is as follows:

The desktop Seagate hard disk object corresponds to the desktop Seagate hard disk object behavior, the notebook IBM hard disk corresponds to the notebook IBM hard disk behavior, this is a typical parallel hierarchical structure.

It is mainly used to separate some behaviors in a class hierarchy, so that classes in the class hierarchy can delegate their own principles to the classes that are separated for implementation, so that the class hierarchy is simpler, therefore, it is called a parallel class hierarchy.

6. parameterization factory Method

Definition: The Factory method is used to pass parameters. Different product objects are created based on different parameters.

Sample Code for scenario problems:

 

Package demo05.factorymethod. example7; /*** business function object for data export */public class exportoperate {// no longer abstract class/*** export file *** @ Param type * The export type selected by the user * @ Param data * data to be saved * @ return whether the file is successfully exported */Public Boolean Export (INT type, string data) {// use the factory method exportfileapi API = factorymethod (type); Return API. export (data);}/*** factory method, create the exported file object interface object ** @ Param type * the exported file object interface object * @ return */protected exportfileapi factorymethod (INT type) {exportfileapi API = NULL; // you can specify the type of object to be exported. If (type = 1) {API = new exporttxtfile ();} else if (type = 2) {API = new exportdb () ;}return API ;}}

The client is as follows:

 

Package demo05.factorymethod. example7; public class client {public static void main (string [] ARGs) {// create the Creator object exportoperate operate = new exportoperate (); // convert the input parameters below to test the parameter factory method operate. export (1, "test1 ");}}

Since then, it will become very easy to expand the parametric factory method:

 

Package demo05.factorymethod. example7;/*** extends the exportoperate object and adds the XML file */public class exportoperate2 extends exportoperate {/*** to overwrite the factory method of the parent class, create the exported file object interface object ** @ Param type * the exported file object interface object * @ return */protected exportfileapi factorymethod (INT type) {exportfileapi API = NULL; // You can overwrite all the data or overwrite the data that you are interested in. // you only want to add your own new implementations here, others, whether if (type = 3) {API = new exportxml ();} else {// others, or let the parent class implement API = super. factorymethod (type);} return API ;}}

The client implementation is also very easy. The Code is as follows:

Package demo05.factorymethod. example7; public class client {public static void main (string [] ARGs) {// create the Creator object exportoperate operate = new exportoperate2 (); // convert the input parameters below to test the parameter factory method operate. export (1, "test1"); operate. export (2, "Test2"); operate. export (3, "test3 ");}}

 7. Advantages and disadvantages of the factory method model:

Advantage: You can program without knowing the specific implementation.

It is easier to expand the version of the new object.

Connecting parallel class Layers

Disadvantages: coupling between specific product objects and factory methods

8. Think about the factory method mode:

Essence: it is implemented only when the latency reaches the subclass.

Note: When selecting implementation, it may feel like a simple factory model. In fact, the specific implementation is "select implementation", but the difference is that a simple factory is implemented in a factory, the factory method will delay this work to sub-classes for implementation.

9. embodiment of Design Principles

The factory method mode reflects the "Dependency inversion principle"

The principle of dependency inversion tells us that we need to rely on abstraction rather than specific classes.

10. Experiences

This factory method is really cool. I have understood it for several days. To tell the truth, it is hard to understand it. Now I am only in the phase of understanding it. I have not finished it. I will write it first, understanding later

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.