search
HomeJavajavaTutorialHow to implement the factory pattern of Java design patterns

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),