Home >Java >javaTutorial >Detailed explanation of Java factory method pattern

Detailed explanation of Java factory method pattern

WBOY
WBOYforward
2022-04-02 12:45:374740browse

This article brings you relevant knowledge about java, which mainly introduces issues related to the factory method pattern. The factory method pattern is also called the virtual constructor pattern or the polymorphic factory pattern. It It belongs to the class creation mode, I hope it will be helpful to everyone.

Detailed explanation of Java factory method pattern

Recommended study: "java tutorial"

1. What is the factory method pattern?

Factory method pattern: also called virtual constructor pattern or polymorphic factory pattern, it belongs to class creation pattern.

In the factory method pattern, the factory parent class is responsible for defining the public interface for creating product objects, while the factory subclass is responsible for generating specific product objects. The purpose of this is to instantiate the product class The operation is deferred to the factory subclass, that is, the factory subclass is used to determine which specific product class should be instantiated.

We know that the division of labor in today's real factories is becoming more and more detailed and specialized. . Various products are produced in specialized factories, completely bidding farewell to the era of self-sufficient small-scale farmer economy, which greatly shortens the production cycle of products and improves production efficiency. The factory method pattern not only satisfies the opening and closing principle, but also inherits the advantages of the simple factory pattern.

Example:

In the Coke factory in the simple factory pattern article, because there is only one factory class, any product needs to be modified and modified in this class Adjustment, and the factory method model is to have multiple factories, each factory produces one product. If there is a need to add new products, we can directly create a new factory, and there is no need to modify it inside other factories, so it is consistent with The opening and closing principle.

2. Advantages and Disadvantages of Factory Method Pattern

Advantages:

  • Users only need to know the name of the specific factory To get the product you want, you don’t need to know the specific creation process of the product

  • Increased flexibility. For the creation of new products, you only need to write one more corresponding factory class

  • Typical decoupling framework. High-level modules only need to know the abstract class of the product and do not need to care about other implementation classes, satisfying Demeter's law, dependency inversion principle and Richter substitution principle

Disadvantages:

  • It is easy to have too many classes, which increases the complexity

  • It increases the abstraction and difficulty of understanding the system

  • Abstract products can only produce one product. This drawback can be solved using Abstract Factory Pattern (Abstract Factory Pattern is in the next article)

3. Structure and implementation of the pattern

The structure consists of the following four parts:

  • Abstract Factory: Provides an interface for creating products, and the caller passes It accesses the factory method newProduct() of the concrete factory to create products

  • Concrete Factory (ConcreteFactory): It mainly implements the abstract methods in the abstract factory and completes the creation of specific products

  • Abstract product (Product): defines the specifications of the product and describes the main features and functions of the product

  • Concrete product (ConcreteProduct): implements the abstract product The interface defined by the role is created by a specific factory, and it has a one-to-one correspondence with the specific factory

Structure diagram:

Detailed explanation of Java factory method pattern

4. Factory method pattern code implementation

Let’s take the Coke factory from the previous article as an example:
Products include: Coca-Cola, Pepsi-Cola, Sugar-Free Coke
In the simple factory pattern, there is only one Coke factory, which can produce three products. In the factory method pattern, there can be multiple factories to generate corresponding products:

Abstract factory: Cola Factory (can be understood as the main factory)
Pepsi-Cola Factory: Generate Pepsi-Cola
Coca-Cola Factory: Generate Coca-Cola
Sugar-free Coke Factory: Generate sugar-free Coke

Method to produce Coke:

/**
 *  提供了产品的接口
 */public interface Cola {

    //生产可乐的方法
    public void cola();}

Cola Abstract Factory:

/**
 * 可乐抽象工厂(可以理解成可乐总厂,旗下还有很多分厂)
 */public interface ColaFactory {

    public Cola newCola();}

Methods to generate three types of cola:
Coke Coke:

/**
 * 产品名称:可乐可乐,实现了产品的接口
 */public class CocaCola implements Cola{

    @Override
    public void cola() {
        System.out.println("开始生产可口可乐");
    }}

Pepsi Cola:

/**
 *
 * 产品名称:百事可乐,实现了产品的接口
 */public class PepsiCola implements Cola{

    @Override
    public void cola() {
        System.out.println("开始生产百事可乐");
    }}

Sugar-free Coke:

/*
 * 产品名称:无糖可乐,实现了产品的接口
 */public class SugarFreeCola implements Cola{

    @Override
    public void cola() {
        System.out.println("开始生产无糖可乐");
    }}

Three products correspond Three factories:

The factory that produces Coca-Cola:

/**
 *
 * 具体工厂1:可口可乐工厂
 */public class CocaColaFactory implements ColaFactory{
    
    @Override
    public Cola newCola() {
        System.out.println("我是可乐工厂下面的可口可乐工厂");
        return new CocaCola();
    }}

The factory that produces Pepsi-Cola:

/**
 *
 * 具体工厂2:百事可乐工厂
 */public class PepsiColaFactory implements ColaFactory{

    @Override
    public Cola newCola() {
        System.out.println("我是可乐工厂下面的百事可乐工厂");
        return new PepsiCola();
    }}

The factory that produces sugar-free Coke:

/*
 * 具体工厂3:无糖可乐工厂
 */public class SugarFreeColaFactory implements ColaFactory{
    
    @Override
    public Cola newCola() {
        System.out.println("我是可乐工厂下面的无糖可乐工厂");
        return new SugarFreeCola();
    }}

Here we are:

  • A method of producing Coke

  • A Coke factory (there are multiple small ones below) Factory)

  • Three methods to produce three types of Coke (implementing the Coke interface)

  • Three Coke factories (to produce three types of Coke, Implementing the Coke factory interface)

Test class:

public class Test {
    public static void main(String[] args) {

        try{

            //新建一个可乐方法对象
            Cola a;

            //新建一个可乐工厂对象
            ColaFactory af;

            //告诉可乐工厂,你需要什么可乐,并且通知对应的分工厂
            af = (ColaFactory) new PepsiColaFactory();
            //执行对于生产方法
            a = af.newCola();
            a.cola();
            
        }catch (Exception e ){
            System.out.println(e.getMessage());
        }
    }}

For example, if I need Pepsi now, I pass the Pepsi factory in af:

我是可乐工厂下面的无糖可乐工厂
开始生产无糖可乐

如果传入CocaColaFactory

我是可乐工厂下面的可口可乐工厂
开始生产可口可乐

5、总结

这就是工厂方法模式,和简单工厂模式有所不同,在这个模式内有一个抽象工厂接口,也就是你需要增加新产品后,不需要在原本的工厂内去修改代码,而是直接新建一个工厂,去实现抽象工厂即可,也是符合了开闭原则。

当然缺点也就是工厂多了,管理变得复杂,也增加了系统的抽象性和理解难度,而且抽象产品只能生产一种产品,但是此弊端可使用抽象工厂模式解决(抽象工厂模式在下一篇文章)

推荐学习:《java教程

The above is the detailed content of Detailed explanation of Java factory method pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete