Home Java javaTutorial JAVA design pattern abstract factory pattern

JAVA design pattern abstract factory pattern

Mar 18, 2017 am 10:49 AM

We have already introduced the simple Factory Pattern and Factory Method Pattern. Here we will continue to introduce the third factory pattern - Abstract Factory Pattern, again taking the manufacturing of cars as an example.

Example background:

As customers’ requirements become higher and higher, BMW cars require different configurations of air conditioners, engines and other accessories. So the factory began to produce air conditioners and engines for assembling cars. At this time, the factory has two series of products: air conditioners and engines. The BMW 320 series is equipped with model A air conditioner and model A engine, and the BMW 230 series is equipped with model B air conditioner and model B engine.

Concept:

The abstract factory pattern is an upgraded version of the factory method pattern. It is used to create a set of related or interdependent objects. For example, the BMW 320 series uses air conditioner model A and engine model A, while the BMW 230 series uses air conditioner model B and engine model B. Then using the abstract factory pattern, when producing related accessories for the 320 series, there is no need to specify the model of the accessory. It will Automatically produce the corresponding accessory model A according to the car model.

In view of the introduction to the abstract factory pattern on Baidu Encyclopedia, combined with this example:

When each abstract product has more than one specific subcategory (air conditioners have models A and B, and engines also have model A and B), how does the factory role know which subclass to instantiate? For example, each abstract product role has two specific products (product air conditioner has two specific products, air conditioner A and air conditioner B). The abstract factory pattern provides two specific factory roles (BMW 320 series factory and BMW 230 series factory), which correspond to these two specific product roles respectively. Each specific factory role is only responsible for the instantiation of a certain product role. Each concrete factory class is only responsible for creating instances of a specific subclass of the abstract product.

Abstract Factory Pattern Code

Product Category:

//发动机以及型号    
public interface Engine {    
  
}    
public class EngineA extends Engine{    
    public EngineA(){    
        System.out.println("制造-->EngineA");    
    }    
}    
public class EngineBextends Engine{    
    public EngineB(){    
        System.out.println("制造-->EngineB");    
    }    
}    
  
//空调以及型号    
public interface Aircondition {    
  
}    
public class AirconditionA extends Aircondition{    
    public AirconditionA(){    
        System.out.println("制造-->AirconditionA");    
    }    
}    
public class AirconditionB extends Aircondition{    
    public AirconditionB(){    
        System.out.println("制造-->AirconditionB");    
    }    
}
Copy after login

Create Factory Class:

//创建工厂的接口    
public interface AbstractFactory {    
    //制造发动机  
    public Engine createEngine();  
    //制造空调   
    public Aircondition createAircondition();   
}    
  
  
//为宝马320系列生产配件    
public class FactoryBMW320 implements AbstractFactory{    
        
    @Override    
    public Engine createEngine() {      
        return new EngineA();    
    }    
    @Override    
    public Aircondition createAircondition() {    
        return new AirconditionA();    
    }    
}    
//宝马523系列  
public class FactoryBMW523 implements AbstractFactory {    
    
     @Override    
    public Engine createEngine() {      
        return new EngineB();    
    }    
    @Override    
    public Aircondition createAircondition() {    
        return new AirconditionB();    
    }    
  
  
}
Copy after login

Customer:

public class Customer {    
    public static void main(String[] args){    
        //生产宝马320系列配件  
        FactoryBMW320 factoryBMW320 = new FactoryBMW320();    
        factoryBMW320.createEngine();  
        factoryBMW320.createAircondition();  
            
        //生产宝马523系列配件    
        FactoryBMW523 factoryBMW523 = new FactoryBMW523();    
        factoryBMW320.createEngine();  
        factoryBMW320.createAircondition();  
    }    
}
Copy after login

Regarding the difference between Abstract Factory Pattern and Factory Method Pattern, I won’t go into details here. I feel like reading the examples several times You can understand it, but there are many mentioned concepts such as product family and hierarchical structure, which are even more difficult to understand.

The origin of the abstract factory pattern

The following is a quote from the origin of the abstract factory pattern:

The origin or earliest application of the abstract factory pattern is used to create window structures belonging to different operating systems. For example: the command button (Button) and the text box (Text) are both window structures. In the window environment of the UNIX operating system and the window environment of the Windows operating system, these two structures have different local implementations, and their details are different. .

In every operating system, there is a build family consisting of window builds. Here is the product family composed of Button and Text. Each window component forms its own hierarchical structure, with an abstract role giving an abstract functional description, and concrete subclasses giving specific implementations under different operating systems.

JAVA design pattern abstract factory pattern

You can find that in the product class diagram above, there are two product hierarchical structures, namely the Button hierarchical structure and the Text hierarchical structure. There are two product families at the same time, namely the UNIX product family and the Windows product family. The UNIX product family consists of UNIX Button and UNIX Text products; the Windows product family consists of Windows Button and Windows Text products.

JAVA design pattern abstract factory pattern

The system’s creation requirements for product objects are met by a project’s hierarchical structure, in which there are two specific project 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 the abstract factory pattern. The solution of the abstract factory pattern is as follows:

JAVA design pattern abstract factory pattern

Obviously, a system can only run in the window environment of a certain operating system, and cannot run 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 scope of use of the abstract factory pattern has been greatly expanded, and the system is no longer required to consume only a certain product family.

Summary:

Whether it is a simple factory pattern, a factory method pattern, or an abstract factory pattern, they all belong to the factory pattern and are very similar in form and characteristics. Their ultimate goal is to decouple. When using it, we don't have to worry about whether this pattern is a factory method pattern or an abstract factory pattern, because the evolution between them is often confusing. Often you will find that when new requirements come and a new method is added to the factory method pattern that is clearly used, it becomes the abstract factory pattern because the products in the class constitute product families in different hierarchical structures. For the abstract factory pattern, when one method is reduced so that the provided products no longer constitute a product family, it evolves into the factory method pattern.

So, when using the factory pattern, you only need to care about whether the purpose of reducing coupling is achieved.

For more articles related to the Abstract Factory Pattern of JAVA design patterns, please pay attention to the PHP Chinese website!

Related articles:

Detailed explanation of the specific code to implement the abstract factory pattern in Java

Comparison of PHP simple factory pattern, factory method pattern and abstract factory pattern

PHP object-oriented development - abstract factory pattern

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles