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

How to implement the factory pattern of Java design patterns

May 23, 2023 pm 06:49 PM
java

The details are as follows:

The factory mode mainly provides a transition interface for creating objects, so as to shield and isolate the specific process of creating objects to achieve the purpose of improving flexibility

The factory mode is divided into There are three categories:

1) Simple Factory: Not conducive to producing series of products;
2) Factory Method: also known as polymorphic factory;
3) Abstract Factory pattern (Abstract Factory): Also known as toolbox, it produces product families, but is not conducive to producing new products;

1. Simple factory pattern

Simple factory pattern is also called static factory method pattern. It can be seen from the renaming that this mode must be very simple. Its purpose is simple: to define an interface for creating objects.
In the simple factory pattern, a factory class is at the center of the product class instantiation call. It determines which product class should be instantiated, just like a traffic policeman standing in the flow of passing vehicles and deciding to let which ones pass. Vehicles in one direction flow in that direction. Let’s take a look at its composition first:

1) Factory role: This is the core of this model and contains certain business logic and judgment logic. In java it is often implemented by a concrete class.
2) Abstract product role: It is generally the parent class inherited by a specific product or the interface implemented. It is implemented in java by interface or abstract class.
3) Specific product role: The object created by the factory class is an instance of this role. Implemented by a concrete class in java.

2. Factory method pattern

The factory method pattern is a further abstraction and promotion of the simple factory pattern. The factory method pattern is no longer determined by only one factory class. The decision that a product class should be instantiated is left to the subclasses of the abstract factory. Let’s take a look at its composition:

1) Abstract factory role: This is the core of the factory method pattern, and it has nothing to do with the application. It is the interface that a specific factory role must implement or the parent class that must be inherited. In java it is implemented by abstract classes or interfaces.
2) Specific factory role: It contains code related to specific business logic. Called by an application to create an object corresponding to a specific product.
3) Abstract product role: It is the parent class inherited by a specific product or the interface implemented. In Java, there are generally abstract classes or interfaces to implement.
4) Specific product role: The object created by the specific factory role is an instance of this role. It is implemented by specific classes in java.

The factory method pattern uses multiple subclasses inherited from the abstract factory role to replace the "God class" in the simple factory pattern. As mentioned above, this shares the pressure on the object; and this makes the structure more flexible - when a new product (i.e., the upstart car) is produced, as long as it is provided according to the abstract product role and abstract factory role Contracts are generated, which can then be used by customers without having to modify any existing code. It can be seen that the structure of the factory role also conforms to the opening and closing principle!

The code is as follows:

//抽象产品角色
public interface Moveable {
  void run();
}
//具体产品角色
public class Plane implements Moveable {
  @Override
  public void run() {
    System.out.println("plane....");
  }
}
public class Broom implements Moveable {
  @Override
  public void run() {
    System.out.println("broom.....");
  }
}
//抽象工厂
public abstract class VehicleFactory {
  abstract Moveable create();
}
//具体工厂
public class PlaneFactory extends VehicleFactory{
  public Moveable create() {
    return new Plane();
  }
}
public class BroomFactory extends VehicleFactory{
  public Moveable create() {
    return new Broom();
  }
}
//测试类
public class Test {
  public static void main(String[] args) {
    VehicleFactory factory = new BroomFactory();
    Moveable m = factory.create();
    m.run();
  }
}

3. Abstract Factory Pattern

The code is as follows

//抽象工厂类
public abstract class AbstractFactory {
  public abstract Vehicle createVehicle();
  public abstract Weapon createWeapon();
  public abstract Food createFood();
}
//具体工厂类,其中Food,Vehicle,Weapon是抽象类,
public class DefaultFactory extends AbstractFactory{
  @Override
  public Food createFood() {
    return new Apple();
  }
  @Override
  public Vehicle createVehicle() {
    return new Car();
  }
  @Override
  public Weapon createWeapon() {
    return new AK47();
  }
}
//测试类
public class Test {
  public static void main(String[] args) {
    AbstractFactory f = new DefaultFactory();
    Vehicle v = f.createVehicle();
    v.run();
    Weapon w = f.createWeapon();
    w.shoot();
    Food a = f.createFood();
    a.printName();
  }
}

In the abstract factory pattern, abstract products (AbstractProduct) may be one or more, thus forming one or more product families (Product Family). In the case of only one product family, the abstract factory pattern actually degenerates into the factory method pattern.

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

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1598
276
What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Building Cloud-Native Java Applications with Micronaut Building Cloud-Native Java Applications with Micronaut Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Fixed: Windows Is Showing 'A required privilege is not held by the client' Fixed: Windows Is Showing 'A required privilege is not held by the client' Aug 20, 2025 pm 12:02 PM

RuntheapplicationorcommandasAdministratorbyright-clickingandselecting"Runasadministrator"toensureelevatedprivilegesaregranted.2.CheckUserAccountControl(UAC)settingsbysearchingforUACintheStartmenuandsettingtheslidertothedefaultlevel(secondfr

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

See all articles