Home Java javaTutorial Learning: java design pattern—factory pattern

Learning: java design pattern—factory pattern

Dec 15, 2016 pm 01:35 PM
java factory pattern

1. The factory pattern 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.



Factory pattern is divided into three categories in "Java and Patterns":
1) Simple Factory pattern (Simple Factory): not conducive to producing a series of products;

2) Factory Method pattern (Factory Method): and Called polymorphic factories; )3) abstract factory model (ABSTRACT Factory): also known as a toolbox, produce product family, but it is not conducive to new products; More general.模 GOF divided the factory model into two categories in the book "Design Model": Factory Method and abstract factory mode. Think of the Simple Factory pattern as a special case of the Factory Method pattern, and the two are classified into the same category.


2. Simple Factory Pattern

The simple factory pattern is also called the 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 instantiation call of a product class. It determines which product class should be instantiated, just like a traffic policeman standing in the flow of passing vehicles and deciding to let them go. 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, containing 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.

3. Factory Method Pattern


Factory Method Pattern is a further abstraction and promotion of the Simple Factory Pattern. In the Factory Method Pattern, it is no longer just a factory class that determines which product class should be instantiated. This decision is handed over to A subclass of the abstract factory does it.
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 flexible - when a new product (i.e., the upstart's 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!

Code:

//抽象产品角色
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();
    }
}
Copy after login


It can be seen that the addition of factory methods has doubled the number of objects. When there are many types of products, a large number of corresponding factory objects will appear, which is not what we want. Because if this situation cannot be avoided, you can consider using a combination of the simple factory pattern and the factory method pattern to reduce factory classes: that is, use a simple factory for similar types on the product tree (usually brothers among the leaves of the tree) mode to achieve.

4. Comparison between simple factory and factory method patterns

The difference in definition between factory method pattern and simple factory pattern is obvious. The core of the factory method pattern is an abstract factory class, unlike the simple factory pattern, which puts the core on a real class. The factory method pattern allows many real factory classes to inherit from the abstract factory class, which can actually become a synthesis of multiple simple factory patterns, thus popularizing the simple factory pattern.
On the other hand, the simple factory pattern is degenerated from the factory method pattern. Imagine that if we are very sure that a system only needs a real factory class, then we might as well merge the abstract factory class into the real factory class. And in this way, we have degraded to the simple factory model.

5. Abstract Factory Pattern

Code:

//抽象工厂类

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

In the Abstract Factory pattern, there may be one or more abstract products (AbstractProduct), 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.


6. Summary.

(1) The simple factory pattern uses a specific class to create instances of other classes. The parent class is the same and the parent class is specific.
(2) The factory method pattern has an abstract parent class defining a public interface, and the subclass is responsible for generating specific objects. The purpose of this is to delay the instantiation of the class to the subclass.
(3) The abstract factory pattern provides an interface for creating a series of related or interdependent objects without specifying their specific classes. It targets hierarchical structures with multiple products. The factory method pattern is aimed at the hierarchical structure of a product.


For more learning: java design pattern - factory pattern related articles, please pay attention to 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

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

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

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

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles