Home > Java > javaTutorial > How to implement the abstract factory pattern of Java design patterns

How to implement the abstract factory pattern of Java design patterns

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-29 14:19:06
forward
928 people have browsed it

1. Introduction

When the system is ready to provide users with a series of related objects, but does not want user code to be coupled to these objects, the abstract factory pattern can be used.

2. How to realize

1) Abstract product--Car

2) Specific product--BYDCar, TSLCar

3) Abstract factory Factory

4) Specific factory--BYDFactory, TSLFactory

3. Code implementation

/**
 * 抽象产品
 */
public abstract class Car {
    public abstract String getName();
}
Copy after login
/**
 * 具体产品
 */
public class BYDCar extends Car {
    String name;
    public BYDCar(String name){
        this.name = name;
    }
    @Override
    public String getName() {
        return name;
    }
}
Copy after login
/**
 * 抽象工厂
 */
public abstract class CarFactoty {
    public abstract Car createCar(String name);
}
Copy after login
 /**
 * 具体工厂
 */
public class BYDFactory extends CarFactoty {
    @Override
    public BYDCar createCar(String name) {
        return new BYDCar(name);
    }
}
Copy after login

4. Summary

1) The abstract factory pattern can create a Series-related objects decouple users from objects of these classes

2) Using the abstract factory pattern can conveniently configure a series of objects for users.

3) In the abstract factory pattern, you can add a "concrete factory" at any time to provide users with a set of related objects.

For example: In the above example, if the user needs a Tesla car, it can be completed by creating a Tesla object and a Tesla factory.

/**
 * 具体产品
 */
public class TSLCar extends Car {
    String name;
    public TSLCar(String name){
        this.name = name;
    }
    @Override
    public String getName() {
        return name;
    }
}
Copy after login
rrree

The above is the detailed content of How to implement the abstract factory pattern of Java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template