Home  >  Article  >  Java  >  How to implement Java factory method pattern

How to implement Java factory method pattern

王林
王林forward
2023-05-20 22:19:151149browse

How to implement Java factory method pattern


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. Following Demeter's Law, Dependency Inversion Principle and Richter Substitution Principle, high-level modules only need to access the abstract class of the product without considering other implementation classes

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:

How to implement 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:

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

If passed in CocaColaFactory:

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

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

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