Java and patterns 26-3rd-Abstract Factory Models

Source: Internet
Author: User
Scenario Problems

A common example in our daily life is assembling a computer. When assembling a computer, we usually need to select a series of accessories, such as CPU, hard disk, memory, motherboard, power supply, and chassis. For the sake of simplicity, we only need to consider the choice of CPU and motherboard.

In fact, when selecting a CPU, there are a series of problems, such as the brand, model, number of pins, and clock speed. Only by determining these problems can we determine the specific CPU.

Similarly, when selecting a motherboard, there are also a series of problems, such as brand, chipset, integrated chip, bus frequency, and so on. Only these problems are identified can the specific motherboard be determined.

Choosing a different CPU and motherboard is the requirement that each customer puts forward to the installation company when assembling a computer, that is, the installation solution developed by each of us.

Before final determining the installation scheme, we also need to consider the compatibility between various accessories as a whole. For example, CPU and motherboard cannot be assembled if Intel CPU and AMD motherboard are used. Because the number of Intel CPU pins is not compatible with the CPU plug-in provided by the amd motherboard, that is to say, if Intel's CPU is used, it cannot be inserted into the amd motherboard, so the installation solution is holistic, the selected accessories are associated.

For the installation engineer, he only knows how to assemble a computer and the relevant accessories, but the customer has to say what kind of accessories to use. That is to say, the installation engineer is only responsible for assembly, and the customer is responsible for selecting the specific accessories required for assembly. Therefore, when the installation engineers assemble computers for different customers, they only need to obtain the corresponding accessories according to the customer's installation scheme and then assemble the computers.

Simple factory solution

Considering the customer's functions, You need to select the CPU and motherboard you need, and then tell the installation engineer their choice, and then wait for the installation engineer to assemble the computer.

For installation engineers, they only know the interfaces of CPU and motherboard, but do not know the specific implementation. Obviously, they can use the simple factory mode or factory method mode. For simplicity, a simple factory is used here. The customer informs the installation engineer of his or her choice, and then the installation engineer obtains the corresponding instance object through the corresponding factory.

Source code

CPU interface and implementation

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:39:35 ** @ Class description: CPU interface class */public interface CPU {public void calculate ();}

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:45:34 ** @ Class description: intelcpu */public class intelcpu implements CPU {/*** Number of CPU pins */private int pins = 0; Public intelcpu (INT pins) {This. pins = pins;} @ overridepublic void calculate () {system. out. println ("Intel CPU pins:" + pins );}}

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:53:12 ** @ Class description: amdcpu */public class amdcpu implements CPU {/*** Number of CPU pins */private int pins = 0; Public amdcpu (INT pins) {This. pins = pins;} @ overridepublic void calculate () {// todo auto-generated method stubsystem. out. println ("amd cpu pins:" + pins );}}

Motherboard interface and implementation

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:53:57 ** @ Class description: motherboard interface */public interface mainboard {public void installcpu ();}

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:56:02 ** @ Class description: intel motherboard class */public class intelmainboard implements mainboard {/*** number of holes in the CPU slot */private int cpuholes = 0;/*** constructor, number of holes passed in the CPU slot ** @ Param cpuholes */Public intelmainboard (INT cpuholes) {This. cpuholes = cpuholes;} @ overridepublic void installcpu () {// todo auto-generated method stubsystem. out. println ("the number of CPU slot holes on the Intel motherboard is:" + cpuholes );}}

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:56:51 ** @ Class description: AMD motherboard */public class amdmainboard implements mainboard {/*** number of holes in the CPU slot */private int cpuholes = 0;/*** constructor, number of holes passed in the CPU slot ** @ Param cpuholes */Public amdmainboard (INT cpuholes) {This. cpuholes = cpuholes;} @ overridepublic void installcpu () {// todo auto-generated method stubsystem. out. println ("amd motherboard CPU slot holes:" + cpuholes );}}

CPU and motherboard Factory

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:57:56 ** @ Class description: CPU factory class */public class cpufactory {public static CPU createcpu (INT type) {CPU = NULL; If (type = 1) {CPU = new intelcpu (755 );} else if (type = 2) {CPU = new amdcpu (938) ;}return CPU ;}}

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:58:27 ** @ Class description: motherboard factory class */public class mainboardfactory {public static mainboard createmainboard (INT type) {mainboard = NULL; If (type = 1) {mainboard = new intelmainboard (755 );} else if (type = 2) {mainboard = new amdmainboard (938) ;}return mainboard ;}}

The running results of installation engineers and customers are as follows:

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:59:14 ** @ Class description: installation engineer */public class computerengineer {/*** defines the CPU required for Assembly */private CPU = NULL; /*** defines the motherboard required for Assembly */private mainboard = NULL; Public void makecomputer (INT cputype, int mainboard) {/*** basic steps for machine assembly * // 1: first, prepare the required accessories preparehardwares (cputype, mainboard); // 2: assemble the machine // 3: test Machine // 4: Delivery customer} private void Preparehardwares (INT cputype, int mainboard) {// here we are going to prepare the specific implementation of the CPU and motherboard. For the sake of simplicity, only the two are prepared here. // However, the installation engineer does not know how to create it. What should I do? // Directly find the corresponding factory to obtain this. CPU = cpufactory. createcpu (cputype); this. mainboard = mainboardfactory. createmainboard (mainboard); // test whether the accessory is easy to use this. CPU. calculate (); this. mainboard. installcpu ();}}

 

Package COM. bankht. abstractfactory; import Org. JUnit. test;/*** @ Author: -AK47 * @ Creation Time: 05:01:04, December 19, ** @ Class description: Customer test class */public class client {@ testpublic void test () {computerengineer cf = new computerengineer (); cf. makecomputer (1, 1 );}}

The running result is as follows:

The above implementation, although solved through a simple factory method: For installation engineers, only the CPU and motherboard interfaces are known, but not the specific implementation problems.But there is another problem that cannot be solved, that is, these CPU objects and the main board objects are actually related and need to match each other.In the above implementation, this association is not maintained, and the CPU and motherboard are chosen by the customer at will, which is problematic. For example, when the client calls makecomputer, the input parameter is (1, 2) and the running result is as follows:

Observe the above results to see the problem. The customer chose intel with 755 CPU pins, AMD as the motherboard, and 938 as the CPU Jack on the motherboard, which cannot be assembled at all, this is because the relationship between accessories is not maintained. How can this problem be solved?

Introduce Abstract Factory Model

Each mode is a solution to certain problems. The biggest difference between the abstract factory mode and the factory method mode is that the factory method mode is for a product level structure, while the abstract factory mode needs to face multiple product level structures.

Before learning the specific example of an abstract factory, we should understand two important concepts: Product Family and product level.

A product family is a family of products with functions associated with different product levels. For example, AMD's motherboard, chipset, and CPU constitute a family, while Intel's motherboard, chipset, and CPU constitute a family. Both families come from three product levels: motherboard, chipset, and CPU. A hierarchical structure consists of products with the same structure, as shown below:

Obviously, each product family contains the number of products, which is equal to the number of product level structures. The hierarchical structure and product family of the product divide the product in different directions to form a two-dimensional coordinate system. The horizontal axis indicates the product level structure, and the vertical axis indicates the product family. There are two product families distributed in three different product level structures. You only need to specify the product family of a product and its hierarchical structure.

The preceding three different hierarchical structures have parallel structures. Therefore, if the factory method is used, it is necessary to use three independent factory level structures to deal with these three product levels. The similarity between the three product levels leads to three parallel factory levels. As the number of product level structures increases, the number of factory level structures given by the factory method model also increases. For example:

So can we use the same factory level structure to deal with these same or extremely similar product levels? Of course, this is the benefit of the abstract factory model. The same factory level structure is responsible for the creation of product objects in three different product levels.

 

It can be seen that a factory level structure can create all objects in a product family with different product levels. Obviously, the abstract factory mode is more efficient than the simple factory mode and factory method mode at this time. Each product family has a specific factory. Each specific factory is responsible for creating products that belong to the same product family but belong to different levels of structure.

Abstract factory pattern structure

Abstract Factory mode is the object creation mode, which is further promoted by the factory method mode.

Assume that a sub-system requires some product objects, and these products belong to more than one product level structure. Abstract Factory models can be introduced to separate the responsibility for consuming these product objects from the responsibility for creating these product objects. In this way, the consumer party does not need to directly participate in the creation of the product, but only needs to request the required product from a public factory interface.

By using the abstract factory mode, you can create product objects in multiple product families with the same (or similar) level structure. As shown in:

Because the two product families have the same hierarchical structure, the same factory family can be used to create the two product families. This is the abstract factory model.

According to the structure diagram of the Product role, it is not difficult to give the structure design diagram of the factory role.

It can be seen that each factory role has two factory methods to create product objects belonging to different product levels.

Source code

The CPU interface and CPU implementation object implemented in the preceding example do not need to be changed.

In the preceding exampleCPUSimple factory and CreationMotherboardIs no longer needed.

Newly Added Abstract Factory classes and implementation classes:

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 05:50:28 ** @ Class description: */public interface abstractfactory {/*** create CPU object ** @ return CPU object */Public CPU createcpu (); /*** create a motherboard object ** @ return motherboard object */Public mainboard createmainboard ();}

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 05:50:55 ** @ Class description: */public class intelfactory implements abstractfactory {@ overridepublic CPU createcpu () {// todo auto-generated method stubreturn new intelcpu (755);} @ overridepublic mainboard createmainboard () {// todo auto-generated method stubreturn new intelmainboard (755 );}}

 

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 05:51:18 ** @ Class description: */public class amdfactory implements abstractfactory {@ overridepublic CPU createcpu () {// todo auto-generated method stubreturn new intelcpu (938);} @ overridepublic mainboard createmainboard () {// todo auto-generated method stubreturn new intelmainboard (938 );}}

Compared with the preceding implementation, the installation engineer class has the following major changes: from the client side, the CPU and motherboard selection parameters are not input, but directly transmitted to the customer's selected product objects. In this way, the compatibility problem caused by selecting the CPU and motherboard separately is avoided. The customer needs to choose one set, which is a series.

Package COM. bankht. abstractfactory;/*** @ Author: -AK47 * @ Creation Time: 04:59:14 ** @ Class description: installation engineer */public class computerengineer {/*** defines the CPU required for Assembly */private CPU = NULL; /*** defines the motherboard required for Assembly */private mainboard = NULL; Public void makecomputer (abstractfactory AF) {/*** basic steps for machine assembly * // 1: first, prepare the required accessories preparehardwares (AF); // 2: Assembly Machine // 3: Test Machine // 4: Delivery customer} private void preparehardwares (PAIA Ctfactory AF) {// here we need to prepare the specific implementation of the CPU and motherboard. For the sake of simplicity, we only need to prepare the two. // However, the installation engineer does not know how to create them. What should I do? // Directly find the corresponding factory to obtain this. CPU = AF. createcpu (); this. mainboard = AF. createmainboard (); // test whether the accessory is easy to use this. CPU. calculate (); this. mainboard. installcpu ();}}

Client code:

Package COM. bankht. abstractfactory; import Org. JUnit. test;/*** @ Author: -AK47 * @ Creation Time: 05:01:04, December 19, ** @ Class description: Customer test class */public class client {@ testpublic void test () {// create an installation engineer object computerengineer cf = new computerengineer (); // The customer selects and creates the product object that needs to be used abstractfactory AF = new amdfactory (); // inform the installation engineer of the product he/she chooses and ask the installation engineer to assemble the computer cf. makecomputer (AF );}}

The abstract factory function is to create an interface for a series of related objects or mutually dependent objects. Be sure to note that the methods in this interface are not arbitrarily stacked, but a series of related or interdependent methods. For example, the motherboard and CPU used in the above example are used to assemble related objects of a computer. Different Installation Schemes represent a specific computer series.

  
Since a series of objects defined by the abstract factory are usually related or mutually dependent, these product objects constitute a product family, that is, the abstract factory defines a product family.

This brings great flexibility. When switching product families, you only need to provide different abstract factory implementations. That is to say, a product family is switched as a whole.

Under what circumstances should I use the abstract factory model?

  1. A system should not depend on the details of how product instances are created, combined, and expressed. This is important for all forms of factory models.

2. There are more than one product family in this system, and the system only consumes products of one of them.

3. products belonging to the same product family are used together. This constraint must be reflected in the system design.(For example, the Intel motherboard MUST use an Intel CPU or an Intel chipset)

4. The system provides a product library. All products use the same interface, so that the client does not rely on implementation.

Abstract The Origin of the factory Model

The origin or earliest application of the abstract factory model is used to create windows that belong to different operating systems. For example, the command buttons and text boxes are both windows. In the Windows environment of the UNIX operating system and Windows environment of the Windows operating system, the two builds have different local implementations, and their details are different.

In each operating system, there is a Windows build family. Here is the product family composed of buttons and text. Each window component has its own hierarchical structure. An abstract role gives an abstract function description, and a specific sub-class gives specific implementations under different operating systems.

We can see that in the above product class diagram, there are two product level structures: the button level structure and the text level structure. There are two product families, namely the Unix product family and the Windows product family. The UNIX product family consists of UNIX buttons and UNIX text products, while the Windows product family consists of Windows buttons and Windows text products.

The system needs to create product objects to meet the hierarchical structure of a project. Two specific engineering roles are available: unixfactory and windowsfactory. The unixfactory object is used to create products in the Unix product family, while the windowsfactory object is used to create products in the Windows product family. This is the application of the abstract factory model. Solutions for the abstract factory model are as follows:

Obviously, a system can only run in a Windows environment of a certain operating system, rather than running on different operating systems at the same time. Therefore, the system can only consume products belonging to the same product family.

In modern applications, the scope of use of the abstract factory model has been greatly expanded, and the system is no longer required to consume only one product family. Therefore, you can ignore the original intentions mentioned above.

Advantages of abstract factory Model
  • Separation interfaces and Implementations

The client uses an abstract factory to create the required objects, and the client does not know the specific implementation. The client is only for product-oriented interface programming. That is to say, the client is decoupled from the specific product implementation.

  • Easy to switch product families

Because a specific factory implementation represents a product family, for example, from the Intel series to the amd series in the above example, you only need to switch the specific factory.

Disadvantages of abstract factory Model
  • It is not easy to expand new products

If you want to add a new product to the entire product family, you need to modify the abstract factory so that all factory implementation classes can be modified.

 

 

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.