search
HomeJavajavaTutorialJAVA design pattern abstract factory pattern

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");    
    }    
}

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();    
    }    
  
  
}

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();  
    }    
}

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
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
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment