Grinding design mode-factory method mode-5

Source: Internet
Author: User
ArticleDirectory
    • 3.6 think about the factory method model
    • 3.7 related models
3.3 parallel class hierarchy

(1) What is a parallel class hierarchy?
Simply put, if there are two class hierarchies, each class in one class hierarchy has a corresponding class structure in the other class hierarchy, it is called a parallel class hierarchy.
For example, there are many types of Hard Disk objects, such as desktop hard disks and notebook hard disks. In the specific implementation of desktop hard disks, there are different brands such as Seagate and Western Digital, likewise, there are implementations of different brands such as Seagate, Hitachi, and IBM on a laptop hard disk. Hard Disk objects have their own behaviors. For example, hard disks can store data and obtain data from hard disks, different Hard Disk objects correspond to different behavior objects, because different hard disk objects have different implementation methods. If the behavior of the hard disk object and the hard disk object is described separately, the structure shown in Figure 10 is formed:

Figure 10 parallel class hierarchy

The hard disk object is a class level, and the hard disk behavior is also a class level, and the classes in the two classes level correspond. The desktop hard drive objects correspond to the actions of the desktop hard drive inside the hard drive; The Notebook IBM hard drive corresponds to the actions of the notebook IBM hard drive, this is a typical parallel class hierarchy.
What is this parallel class hierarchy used? It is mainly used to separate some behaviors in a class level, so that classes in the class level can delegate their own responsibilities to the classes that are separated for implementation, this makes the class hierarchy simpler and easier to expand and reuse.
Generally, the separated behaviors of these classes are organized according to the class hierarchy to form a new class hierarchy, this is equivalent to the class hierarchy of the behavior of the original object, and this hierarchy corresponds to the original class hierarchy, so it is called a parallel class hierarchy.

(2) What is the relationship between the factory method model and the parallel class hierarchy?
You can use the factory method mode to connect parallel class layers.
See Figure 10 above. In each Hard Disk object, there is a factory method createhdoperate. Through this factory method, the client can obtain a behavior object corresponding to the hard disk object. In the subclass of the hard disk object, it will overwrite the parent class's factory method createhdoperate to provide the behavior object corresponding to itself, so as to naturally connect two parallel classes for use.

3.4 parameterization factory Method

The so-called parametric factory method refers:Passing parameters to the factory method allows the factory method to create different product Objects Based on Different parameters. This situation is called the Parameterized Factory method.. Of course, different products created by the factory method must be of the same product type.
To transform the previous example, there is now a factory method to create the exportfileapi product object, but there are many specific implementations of the exportfileapi interface, in order to facilitate the creation of selection, directly input a parameter from the client, in this way, when you need to create an exportfileapi object, you can pass this parameter to the factory method to let the factory method instantiate a specific exportfileapi implementation object.
Let's take a look.CodeThe example is clear.
(1) Let's take a look at the product interface, that is, the exportfileapi interface. There is no change in the preceding example. To make it easier for you to view it, repeat it here. The sample code is as follows:

/**

* Interface for exported file objects

*/

Public interface exportfileapi {

/**

* Export the content to a file

* @ Param data: indicates the data to be saved.

* @ Return: whether the export is successful

*/

Public Boolean Export (string data );

}

 

(2) It also provides the implementation of saving as a text file and saving as a database backup file. The preceding example does not change. The sample code is as follows:

public class exporttxtfile implements exportfileapi {

Public boolean Export (string data) {

// give a brief description, composition

system. out . println ("export data" + Data + "to text file");

return true;

}

}

public class exportdb implements exportfileapi {

Public Boolean Export (string data) {

// enter the database and file to be operated.

system. out . println ("export data" + Data + "Back up database file");

return true;

}

}

 

(3) let's take a look at the exportoperate class. The changes to this class are roughly as follows:

    • In the exportoperate class, the factory method for creating a product usually needs to provide the default implementation, which is not abstract, that is, the normal method.
    • The exportoperate class is no longer defined as an abstract class. With the default implementation, the client may need to directly use this object.
    • Set an export type parameter and pass it in from the client through the Export Method

Let's look at the code. The sample code is as follows:

/**

* Business function objects for data export

*/

Public class exportoperate {

/**

* Export files

* @ Param type the selected export type

* @ Param data the data to be saved

* @ Return whether the file is exported successfully

*/

Public Boolean Export (INT type, string data ){

// Use the factory Method

Exportfileapi API = factorymethod (type );

Return API. Export (data );

}

/**

* Factory method: Create the interface object of the exported file object

* @ Param type the selected export type

* @ Return interface object of the exported file object

*/

Protected exportfileapi factorymethod (INT type ){

Exportfileapi API = NULL;

//Select which file to create Based on the type. 

If (type = 1 ){

API = new exporttxtfile ();

} Else if (type = 2 ){

API = new exportdb ();

}

Return API;

}

}

 

(4) The client at this time is very simple. Use the exportoperate class directly. The sample code is as follows:

Public class client {

Public static void main (string [] ARGs ){

// Create the Creator object to be used

Exportoperate operate = new exportoperate ();

//Call the Function Method of the output data and input parameters of the everywhere type. 

Operate. Export (1 ,"Test Data");

}

}

 

test and modify the client parameters, and then select the specific export implementation process through the parameters. This is a very common implementation method of Parameterized Factory methods, but it is still abstract to implement Parameterized Factory methods, it doesn't mean that Parameterized Factory methods cannot be implemented as abstract classes. In general, the parameter factory method provides default implementation in the parent class.
(5) New extension implementation
using the Parameterized Factory method, it is very easy to expand , and existing code will not change, you only need to add a new subclass to provide a new factory method implementation, and then use this new subclass on the client.
This implementation method also has an interesting feature, that is, sub-classes can be selectively overwritten. features that do not want to be overwritten can also be returned to implement the parent class, which is very interesting.
first, expand the implementation of an XML file exported. The sample code is as follows:

/**

* Objects exported to XML files

*/

Public class exportxml implements exportfileapi {

Public Boolean Export (string data ){

// A simple illustration

System.Out. Println ("export data" + Data + "to XML file ");

Return true;

}

}

 

Then extend the exportoperate class to add a new implementation. The sample code is as follows:

/**

* Extends the exportoperate object and adds XML files that can be exported.

*/

Public class exportoperate2 extends exportoperate {

/**

* Overwrite the factory method of the parent class and create the interface object of the exported file object

* @ Param type the selected export type

* @ Return interface object of the exported file object

*/

Protected exportfileapi factorymethod (INT type ){

Exportfileapi API = NULL;

//You can overwrite all data or overwrite data that you are interested in, 

//Here, you only want to add your own new implementations. 

If (type = 3 ){

API = new exportxml ();

} Else {

//Others are implemented by the parent class. 

API = super. factorymethod (type );

}

Return API;

}

}

 

Let's look at the client at this time. It's also very simple, just transforming the input parameters. The sample code is as follows:

Public class client {

Public static void main (string [] ARGs ){

// Create the Creator object to be used

Exportoperate operate = new exportoperate2 ();

// Convert the input parameters below to test the parametric factory method.

Operate. Export (1, "test1 ");

Operate. Export (2, "Test2 ");

Operate. Export (3, "test3 ");

}

}

 

The test results are as follows:

Export data from test1 to a text file

Export data Test2 to database backup file

Export data from test3 to XML file

Through the above example, we will take a good look at the implementation and benefits of the parametric factory method.

 

3.5 advantages and disadvantages of the factory method model
    • Programming without knowing the specific implementation
      The factory method mode allows you to use the product interface to implement a specific product object without worrying about the specific implementation. Select the implementation task to be completed by the subclass.
    • It is easier to expand new versions of Objects
      The factory method provides a hook to the subclass, making it easy to extend the new object version. For example, in the implementation of the parametric factory method in the preceding example, the existing code will not change when a new export XML file format is extended, you only need to add a new subclass to provide a new factory method implementation, and then use this new subclass on the client.
      In addition, the hook mentioned here is the hook method we often call. This will be detailed in the template method mode later.
    • Connecting parallel class Layers
      In addition to creating product objects, the factory method also demonstrates its skill in connecting parallel class layers. This is described in detail earlier.
    • Coupling between specific product objects and factory methods
      In the factory method mode, the factory method needs to create product objects, that is, you need to select specific product objects and create their instances, therefore, the specific product object is coupled with the factory method.
3.6 think about the factory method model

1: essence of the factory method model
Essence of the factory method model:Delay to subclass to select implementation.
After carefully understanding the previous example, you will find that the factory method in the factory method mode is usually the specific product implementation object to be used in actual implementation, create an example of the specific product object and then return it. That is to say, the factory method itself does not implement the product interface. The specific product implementation has been written, and the factory method only needs to be selected for implementation.
Some may say, isn't this the same as a simple factory?
In essence, they are very similar. The specific implementations are all "select implementation ". However, there are also differences. A simple factory directly implements "select implementation" in the factory class, and the factory method will delay this work to the subclass for implementation, the factory method in the factory class depends on abstraction rather than concrete implementation, so that the system is more flexible, with better maintainability and scalability.
In fact, if we degrade the creator in the factory model, we only provide factory methods, and these factory methods also provide default implementations, will it become a simple factory? For example, you can take the sample code that demonstrates the parametric factory method and then simplify it. You can see that it is similar to a simple factory. The sample code is as follows:

After reading the above Code, we will see that there is a great similarity between the simple factory and the factory method mode. From a certain point of view, we can think that a simple factory is a special case of the factory method mode, it is not surprising that their nature is similar.

2: embodiment of Design Principles
 The factory method model demonstrates the "Dependency inversion principle ".
The dependency inversion principle tells us that "dependency abstraction is required, rather than dependent on specific classes". Simply put, a high-level component cannot depend on a lower-level component, regardless of whether it is a high-level component or a lower-level component, all should depend on abstraction.
For example, in the previous example, the exportoperate that implements client request operations is the high-level component, and the specific object that implements data export is the lower-level component, such as exporttxtfile and exportdb. The exportfileapi interface is equivalent to that abstraction.
For exportoperate, it does not care about the specific implementation method. It is only "interface-oriented programming". For specific implementation, it only cares about the functions required by "how to implement interfaces.
So what is inverted? The inversion is the "ownership" of this interface ". In fact, all functions defined in the exportfileapi interface are required by the high-level component exportoperate. That is to say, the functions in the interface are required by the high-level component. However, high-level components only propose requirements and do not care about how to implement them. Low-level components actually implement the interface functions required by High-level components. Therefore, it seems that the ownership of the interfaces implemented at the lower layer is not in the hands of the underlying components, but is put to the upper layer components.

3: When to select the factory method mode
We recommend that you use the factory method in the following situations:

    • If a class needs to create an interface object but does not know the specific implementation, you can use the factory method mode to delay the creation of the object to the subclass for implementation.
    • If a class is expected to create the required object by its subclass, the factory method mode should be used.
3.7 related models
    • Factory method mode and abstract factory Mode
      These two modes can be used in combination, specifically in the abstract factory mode.
    • Factory method mode and template method mode
      The two modes are similar in appearance. They all have an abstract class and are then implemented by the subclass. However, the subclass of the factory method mode focuses on creating product objects, the subclass of the template method mode focuses on fixedAlgorithmThe skeleton provides implementation of certain steps.
      These two modes can be used in combination. Generally, in the template method mode, the factory method is used to create the objects required by the template method.

 

==================Factory method mode ended. Thank you!========================
 

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.