The abstract factory model of Java and patterns

Source: Internet
Author: User
Tags prepare

A common example of life-assembling a computer, when we assemble a computer, we usually need to select a range of accessories, such as CPU, hard disk, memory, motherboard, power supply, chassis, etc. To discuss the use of simple points, only consider selecting the CPU and motherboard issues.

In fact, when choosing the CPU, faced with a series of problems, such as brand, model, number of pins, frequency, and so on, only to identify these problems, to determine the specific CPU.

Similarly, in the selection of motherboards, there are a series of problems, such as brand, chipset, integrated chip, bus frequency and other issues, and only these are determined to determine the specific motherboard.

Choose a different CPU and motherboard, is each customer in the assembly of the computer, to the installation company requirements, that is, each of us developed the installation plan.

It is also necessary to consider the compatibility of the individual parts as a whole before finalizing the installation plan. For example: CPU and motherboard, if the use of Intel's CPU and AMD's motherboard is simply unable to assemble. Because Intel's CPU pins are incompatible with the CPU sockets provided by the AMD motherboard, this means that if the Intel CPU is not plugged into AMD's motherboard, the installation plan is holistic and there is an association between the various components selected.

For the installation engineer, he only knows to assemble a computer, need the corresponding accessories, but the specific use of what kind of accessories, but also by the customer to decide. This means that the installation engineer is only responsible for assembling, and the customer is responsible for selecting the specific parts required for assembly. Therefore, when the installation engineer for different customers to assemble the computer, just according to the customer's installation plan, to obtain the corresponding accessories, and then assemble.

Solutions that use simple Factory mode

Consider the customer's function, need to choose their own CPU and motherboard, and then tell the installation engineer their own choice, then wait for the installation engineer to assemble the computer.

For the installation engineer, just know the CPU and motherboard interface, but do not know the implementation, it is obvious that can be used in simple Factory mode or factory method mode. For simplicity, a simple factory is chosen here. The customer tells the installation engineer their own choice, and then the installation engineer will obtain the corresponding instance object through the corresponding factory.

  

Source

CPU interface and specific implementation

Public interface Cpu {
public void calculate ();
}
public class Intelcpu implements CPU {
/**
* Number of pins on the CPU
*/
private int pins = 0;
Public intelcpu (int pins) {
This.pins = pins;
}
@Override
public void Calculate () {
TODO auto-generated Method Stub
System.out.println ("Number of pins for Intel CPUs:" + pins);
}

}
public class Amdcpu implements CPU {
/**
* Number of pins on the CPU
*/
private int pins = 0;
Public amdcpu (int pins) {
This.pins = pins;
}
@Override
public void Calculate () {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("AMD CPU PIN Number:" + pins);
}
}

Motherboard interface and specific implementation

Public interface Mainboard {
public void installcpu ();
}
public class Intelmainboard implements Mainboard {
/**
* Number of holes in the CPU slots
*/
private int cpuholes = 0;
/**
* Construction method, number of holes passed into the CPU slot
* @param cpuholes
*/
Public Intelmainboard (int cpuholes) {
This.cpuholes = Cpuholes;
}
@Override
public void Installcpu () {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("Intel Motherboard CPU Socket Hole number is:" + cpuholes);
}

}
public class Amdmainboard implements Mainboard {
/**
* Number of holes in the CPU slots
*/
private int cpuholes = 0;
/**
* Construction method, number of holes passed into the CPU slot
* @param cpuholes
*/
Public Amdmainboard (int cpuholes) {
This.cpuholes = Cpuholes;
}
@Override
public void Installcpu () {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("AMD Motherboard CPU Socket hole number is:" + cpuholes);
}
}

CPU and Motherboard factory class

public class Cpufactory {
public static CPU createcpu (int type) {
CPU CPU = NULL;
if (type = = 1) {
CPU = new INTELCPU (755);
}else if (type = = 2) {
CPU = new AMDCPU (938);
}
return CPU;
}
}
public class Mainboardfactory {
public static mainboard createmainboard (int type) {
Mainboard mainboard = null;
if (type = = 1) {
mainboard = new Intelmainboard (755);
}else if (type = = 2) {
mainboard = new Amdmainboard (938);
}
return mainboard;
}
}

The operating results of the installation engineer class and the customer class are as follows:

public class Computerengineer {
/**
* Define the CPU required by the Assembly machine
*/
Private CPU CPU = NULL;
/**
* Define the motherboard required for the Assembly machine
*/
Private mainboard mainboard = null;
public void Makecomputer (int cputype, int mainboard) {
/**
* Basic steps for assembling machines
*/
1: First of all the necessary accessories for the installation
Preparehardwares (Cputype, mainboard);
2: Assembling the machine
3: Test machine
4: Customer Delivery
}
private void Preparehardwares (int cputype, int mainboard) {
Here to prepare the CPU and motherboard specific implementation, for example simple, here only the two
However, the installation engineer does not know how to create, how to do?

Find the appropriate factory directly
THIS.CPU = Cpufactory.createcpu (Cputype);
This.mainboard = Mainboardfactory.createmainboard (mainboard);

Test the accessories to be useful
This.cpu.calculate ();
This.mainboard.installCPU ();
}
}

public class Client {
public static void Main (String[]args) {
Computerengineer CF = new Computerengineer ();
Cf.makecomputer (a);
}
}

The results of the operation are as follows:


The above implementation, although the simple factory method solved: For the installation engineer, only know the CPU and motherboard interface, and do not know the specific implementation of the problem. But there is another problem that is not solved, that is, these CPU objects and motherboard objects are actually related, need to match each other. While the above implementation does not maintain this association, the CPU and motherboard are arbitrarily selected by the customer, which is problematic. For example, when the client calls Makecomputer, the incoming parameter is (), and the result is as follows:

Look at the results above and you'll see the problem. The customer chooses the Intel CPU PIN number is 755, but chooses the motherboard is AMD, the motherboard CPU jack is 938, cannot assemble at all, this is not the maintenance accessory the relationship causes. How do we solve this problem?

Introduction of abstract Factory mode

Each model is a solution to a problem. The biggest difference between the abstract factory model and the factory method pattern is that the factory method model is for a product hierarchy, while the abstract factory model requires multiple product hierarchies.

Before you learn the concrete examples of an abstract factory, you should understand two important concepts: product family and product grade.

The so-called product family, is located in the different product hierarchy structure, the function is related to the product composition family. For example, AMD's motherboard, chipset, CPU make up a family, Intel's motherboard, chipset, CPU make up a family. Both families come from three product levels: motherboard, chipset, CPU. A hierarchical structure is made up of products of the same structure, as follows:

Obviously, the number of products in each product family is equal to the number of product grade structures. The product hierarchy and product families divide the product into different directions, forming a two-dimensional coordinate system. The horizontal axis represents the hierarchical structure of the product, and the longitudinal axes represent the product family, with a total of two product families distributed in three different product hierarchy structures. This product can be determined only by specifying the product family in which a product is located and the hierarchy to which it belongs.

The three different hierarchical structures given above have parallel structures. Therefore, if the factory method model is used, it is bound to use three independent plant hierarchy to deal with these three product grade structures. Due to the similarity of the three product hierarchy, three parallel plant hierarchy structures are produced. As the number of product hierarchies increases, the number of factory hierarchy structures given by the factory method pattern increases. Such as:

Can you use the same factory hierarchy to deal with these same or very similar product hierarchies? Of course, and that's the benefit of the abstract factory model. The same factory hierarchy is responsible for the creation of product objects in three different product hierarchy structures.

As you can see, a factory hierarchy can create all of the objects in a product family that belong to different product hierarchy structures. Obviously, abstract Factory mode is more efficient than simple Factory mode and factory method mode. corresponding to each product family has a specific factory. Each specific factory is responsible for creating products belonging to the same product family, but belonging to different hierarchical structures.

Abstract Factory Pattern Structure

Abstract Factory mode is the creation mode of objects, which is a further generalization of the factory method pattern.

Suppose a subsystem requires some product objects, and these products belong to more than one product hierarchy. The abstract factory model can be introduced in order to separate the responsibility for consuming these product objects from the responsibility of creating these product objects. In this case, the consumer product does not need to directly participate in the creation of the product, but only to a common factory interface to request the required products.

By using the abstract factory pattern, you can handle the creation of product objects in multiple product families with the same (or similar) hierarchy. As shown in the following:

  

Because the hierarchy of the two product families is the same, the creation of the two product families can also be handled by using the same factory family, which is the abstract factory pattern.

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

As you can see, each plant role has two factory methods, each of which is responsible for creating product objects that belong to different product hierarchies.

  

Source

The previous example implements the CPU interface and CPU implementation objects, the motherboard interface and the motherboard implementation object, all without changes.

The simple factory that created the CPU in the previous example and the simple factory that created the motherboard are no longer needed.

Newly added abstract factory classes and implementation classes:

Public interface Abstractfactory {
/**
* Create CPU objects
* @return CPU Object
*/
Public Cpu createcpu ();
/**
* Create a Motherboard object
* @return Motherboard Object
*/
Public mainboard Createmainboard ();
}
public class Intelfactory implements Abstractfactory {

@Override
Public Cpu createcpu () {
TODO auto-generated Method Stub
return new INTELCPU (755);
}

@Override
Public mainboard Createmainboard () {
TODO auto-generated Method Stub
return new Intelmainboard (755);
}

}
public class Amdfactory implements Abstractfactory {

@Override
Public Cpu createcpu () {
TODO auto-generated Method Stub
return new INTELCPU (938);
}

@Override
Public mainboard Createmainboard () {
TODO auto-generated Method Stub
return new Intelmainboard (938);
}

}

Installed engineer class compared with the previous implementation, the main change is: From the client is no longer passed in the selection of CPU and motherboard parameters, but directly into the customer has selected a good product object. This avoids the individual to choose the CPU and the motherboard of the compatibility problem, the customer to choose is a set, is a series.

public class Computerengineer {
/**
* Define the CPU required by the Assembly machine
*/
Private CPU CPU = NULL;
/**
* Define the motherboard required for the Assembly machine
*/
Private mainboard mainboard = null;
public void Makecomputer (Abstractfactory af) {
/**
* Basic steps for assembling machines
*/
1: First of all the necessary accessories for the installation
Preparehardwares (AF);
2: Assembling the machine
3: Test machine
4: Customer Delivery
}
private void Preparehardwares (Abstractfactory af) {
Here to prepare the CPU and motherboard specific implementation, for example simple, here only the two
However, the installation engineer does not know how to create, how to do?

Find the appropriate factory directly
THIS.CPU = Af.createcpu ();
This.mainboard = Af.createmainboard ();

Test the accessories to be useful
This.cpu.calculate ();
This.mainboard.installCPU ();
}
}

Client code:

public class Client {
public static void Main (String[]args) {
Create an installed engineer object
Computerengineer CF = new Computerengineer ();
Customers select and create product objects that need to be used
Abstractfactory af = new intelfactory ();
Tell the installation engineer to choose the product and let the installation engineer assemble the computer
Cf.makecomputer (AF);
}
}

The function of an abstract factory is to create an interface for a series of related objects or objects that depend on each other. It is important to note that the methods within this interface are not arbitrarily stacked, but rather a series of interrelated or interdependent methods. For example, the motherboard and CPU in the example above are designed to assemble a computer related object. Different installed solutions, representing a specific computer series.

    
Because a series of objects defined by an abstract factory are usually related or interdependent, these product objects form a product family, which is a product family defined by the abstract factory.

This gives a lot of flexibility when switching product families, as long as the different abstract factory implementations are available, which means that the product family is now switched as a whole.

  

Under what circumstances should the abstract factory pattern be used

  1. A system should not rely on the details of how a product class instance is created, composed, and expressed, which is important for all forms of Factory mode.

2. The product of this system has more than one product family, and the system only consumes the products of one of the families.

3. Products belonging to the same product family are used together, and this constraint must be reflected in the design of the system. (Example: Intel motherboard must use Intel CPU, Intel chipset)

4. The system provides a library of product classes, all products appear on the same interface, so that the client is not dependent on the implementation.

The origin of the abstract factory pattern

The origin or earliest application of the abstract factory pattern is used to create Windows constructs that belong to different operating systems. For example, the command button and text box (text) are all Windows constructs, in the UNIX operating system Windows environment and Windows Operating System window environment, these two constructs have different local implementation, their details are different.

In each operating system, there is a building family consisting of a Windows build. Here is the product family of button and text. Each window component constructs its own hierarchical structure, which is given abstract function description by an abstract role, and the specific subclass gives the specific implementation under different operating systems.

  
It can be found that in the above product class diagram, there are two product hierarchy structures, namely the button hierarchy and the text hierarchy. There are also two product families, namely the UNIX product family and the Windows product family. The UNIX product family consists of a Unix button and a UNIX text product, while the Windows product family consists of Windows button and the Windows text product.

The requirements for the creation of a product object are met by the hierarchy of a project, which has two specific engineering roles, namely Unixfactory and Windowsfactory. The Unixfactory object is responsible for creating products in the Unix product family, while the Windowsfactory object is responsible for creating products in the Windows product family. This is the application of abstract Factory mode, the solution of abstract Factory mode such as:

  

Obviously, a system can only run in a Windows environment of one operating system, but not on different operating systems at the same time. Therefore, the system can actually only consume products belonging to the same product family.

In modern applications, the use of abstract Factory mode has been greatly expanded, no longer require the system to consume only one product family. Therefore, it is not necessary to heed the original intention mentioned earlier.

Advantages of the abstract factory model
    • Separating interfaces and implementations

The client uses an abstract factory to create the objects it needs, and the client simply does not know who the specific implementation is, and the client is simply programming the interface for the product. In other words, the client is decoupled from the specific product implementation.

    • Make it easy to switch product families

Because a specific factory implementation represents a product family, such as the above example from the Intel series to the AMD series only need to switch the specific factory.

Disadvantages of the abstract factory model
    • Not easy to expand new products

If you need to add a new product to the entire product family, then you need to modify the abstract factory, which will result in modifying all of the factory implementation classes.

The abstract factory model of Java and patterns

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.