Home > Java > javaTutorial > body text

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

不言
Release: 2018-09-12 15:54:24
Original
1851 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!