Table of Contents
Preface
Simple Factory Pattern
Factory Method Pattern
Abstract Factory Pattern
Home Java javaTutorial Introduction to Factory Pattern in Java Design Patterns (Code Example)

Introduction to Factory Pattern in Java Design Patterns (Code Example)

Sep 12, 2018 pm 03:54 PM
java design patterns

This article brings you an introduction to the factory pattern in Java design patterns (code examples), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

In the previous article, we learned about the singleton pattern and introduced several methods of creating the singleton pattern as well as the optimal method. This article introduces the factory pattern in design patterns, which is mainly divided into simple factory pattern, factory method and abstract factory pattern.

Simple Factory Pattern

The simple factory pattern is a creational pattern, also called the static factory method pattern. The simple factory pattern uses a factory object to decide which product class instance to create. The call only needs to tell the factory class the required type, and the factory class will return the required subclass of the product class factory. It can be said to be the simplest one among the factory patterns.

For example, we often play games on the computer. We only need to tell the computer what game we want to play, and the computer will open the game. We do not need to care about how the game works.
We can make corresponding explanations in the following code.

We first create a game general class interface, including a method for playing games; then the respective game classes inherit this class and implement the methods of this class, and finally create an engineering class based on different games. Create objects.
Then the implemented code is as follows:

Code example:

    private static final String LOL="LOL"; 
    private static final String DNF="DNF"; 
    
    public static void main(String[] args) {
        Game game= ComputerFactory.playGame(LOL);
        Game game2= ComputerFactory.playGame(DNF);
        game.play();
        game2.play();
    }
}

interface Game{
    void play();
}

class LOL implements Game{
    @Override
    public void play() {
        System.out.println("正在玩LOL...");
    }   
}

class DNF implements Game{
    @Override
    public void play() {
        System.out.println("正在玩DNF...");
    }   
}


class ComputerFactory{
    private static final String LOL="LOL"; 
    private static final String DNF="DNF"; 
     public static Game playGame(String game){
         if(LOL.equalsIgnoreCase(game)){
             return new LOL();
         }else if(DNF.equalsIgnoreCase(game)){
             return new DNF();
         }
         return null;
     }
Copy after login

Output result:

正在玩LOL...
正在玩DNF...
Copy after login

We are using After implementing this function in the simple factory mode, you will find that we put the instantiation of the game class into the factory class, hiding the details of object creation, and you don’t need to know how to play, you only need to know how to call the factory class. . And it is convenient to switch, because you only need to change the type value passed by the factory class.
But we also found a problem. If we need to add a new game class, we need to define a new interface, and then add a judgment branch to the factory class. If it is a small amount, it is fine, but if it is a large amount, it will be more troublesome. , and this also violates the open-closed principle.

Factory Method Pattern

The factory method pattern is one of the most commonly used design patterns in Java and is a creational pattern. Define an interface for creating objects and let its subclasses decide which factory class to instantiate. The factory pattern delays the creation process until the subclasses.

In the simple factory pattern, we found that when adding a subclass, we also need to add a judgment branch to the factory class, which violates the open-closed principle. The factory method pattern mainly solves this problem.

The above example of playing games is still used here, except that each game here is implemented by its own game factory class. The main difference is that there are multiple factory classes instead of one, which reduces the degree of coupling. If you add a new game class, you only need to add a factory class, and the open-closed principle is perfectly followed.

After changing the above code, the corresponding code is implemented as follows:

Code example:

    private static final String LOL="LOL"; 
    private static final String DNF="DNF"; 
    private static final String WOW="WOW"; 

    public static void main(String[] args) {

        Game game3=new LOLFactory().playGame(LOL);
        Game game4=new DNFFactory().playGame(DNF);
        Game game5=new WOWFactory().playGame(WOW);
        game3.play();
        game4.play();
        game5.play();       
    }
    
interface Game{
    void play();
}


class LOL implements Game{
    @Override
    public void play() {
        System.out.println("正在玩LOL...");
    }   
}

class DNF implements Game{
    @Override
    public void play() {
        System.out.println("正在玩DNF...");
    }   
}

class WOW  implements Game{
    @Override
    public void play() {
        System.out.println("正在玩WOW...");
    }   
}


interface ComputerFactory2{
    Game playGame(String game);
}

class LOLFactory implements ComputerFactory2{
    @Override
    public Game playGame(String game) {
        return new LOL();
    }
}

class DNFFactory implements ComputerFactory2{
    @Override
    public Game playGame(String game) {
        return new DNF();
    }
}

class WOWFactory implements ComputerFactory2{
    @Override
    public Game playGame(String game) {
        return new WOW();
    }
}
Copy after login

Output result:

正在玩LOL...
正在玩DNF...
正在玩WOW...
Copy after login

You can see that after using the factory method pattern, our code becomes clearer and the scalability becomes higher. If we want to add a product, we only need to extend a factory class. But what follows is an increase in complexity in the system. Every time a product is added, a concrete class and object implementation factory class need to be added.
So you need to pay attention to whether to use this mode.
The classic use case for using this mode is the famous hibernate framework when choosing a database dialect. But if you just simply new an object, you don't have to use it. If you use it, it will increase the complexity of the system.

Abstract Factory Pattern

The abstract factory pattern creates other factories around a super factory. The Gigafactory is also known as the factory of other factories. This type of design pattern is a creational pattern, which provides an optimal way to create objects. That is, providing an interface for creating a series of related or interdependent objects without specifying their specific classes.

The abstract factory pattern is more complex and difficult to understand than the factory method pattern, but it is easier to extend.
The abstract factory pattern groups product subcategories of the same type into one category, lets them inherit the same abstract subcategory, then treats them as a group, and then groups multiple groups into a family.
For example, still playing the above-mentioned games, we can treat LOL and WOW as PVP type games, or DNF and WOW are treated as PVE type games.

Then the corresponding changed code is as follows:

Code example:

    private static final String LOL="LOL"; 
    private static final String DNF="DNF"; 
    private static final String WOW="WOW"; 
    
    public static void main(String[] args) {

        ComputerFactory3 cf3=new PVPFactory();
        cf3.playGame().play();
        cf3.playGame2().play();
        ComputerFactory3 cf4=new PVEFactory();
        cf4.playGame().play();
        cf4.playGame2().play();         
    }       
}


interface Game{
    void play();
}


class LOL implements Game{
    @Override
    public void play() {
        System.out.println("正在玩LOL...");
    }   
}

class DNF implements Game{
    @Override
    public void play() {
        System.out.println("正在玩DNF...");
    }   
}

class WOW  implements Game{
    @Override
    public void play() {
        System.out.println("正在玩WOW...");
    }   
}


interface ComputerFactory3{
     Game playGame();
     Game playGame2();
}

class PVPFactory implements ComputerFactory3{

    @Override
    public Game playGame() {
        return new LOL();
    }

    @Override
    public Game playGame2() {
        return new WOW();
    }   
}

class PVEFactory implements ComputerFactory3{

    @Override
    public Game playGame() {
        return new DNF();
    }

    @Override
    public Game playGame2() {
        return new WOW();
    }
    
}
Copy after login

Output result:

正在玩LOL...
正在玩WOW...
正在玩DNF...
正在玩WOW...
Copy after login

在抽象工厂模式中,可以在不需要知道产品是怎么样的,只需知道是哪个工厂类就行了。我们也可以根据子类的共同的特性而将它们设计在一起,组成一个相同类型组,可以很方便的直接调用。但是相对的,产品族比较难以扩展,增加一个产品,需要增加相应的接口和实现类。例如某个品牌的手机,有不同系列,每个系列有不同的型号,如果只是增加型号的话,比较容易,但是相对的,增加某个系列就比较麻烦了。
所以我们在使用抽象工厂模式,也需要相应的结合实际场景来使用。

相关推荐:

Java设计模式是什么?Java设计模式中单例模式的介绍

The above is the detailed content of Introduction to Factory Pattern in Java Design Patterns (Code Example). 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

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

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)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles