

Creational Design Pattern Series: Factory Method Pattern
source link: https://www.tuicool.com/articles/hit/J73QBfN
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The factory method design pattern is one of the well-known “Gang of Four” (GoF) design patterns. It is a creational design pattern that uses factory methods to deal with creating instances without specifying the exact class of the object that will be created.
This design pattern is based on one of the OOPs concepts, which is encapsulation. In general, we write object creation code on client side programs, but in the factory pattern, we encapsulate object creation code inside the factory method. So, depending on the data provided to the factory, it can return an object of one of several possible classes listed within a program.
In this article, let us look at a small but complete example of the Factory Pattern.
The pattern basically works as shown below in the UML diagram:
A Person Interface
First, let’s create a Person interface. Any Person that the factory returns must implement this Java interface. We’ll just specify that any class that calls itself a Person must implement a run method.
public interface Person { public void run(); }
Concrete Classes
We will create three concrete classes that implement the Person interface. This is an important part of the Factory Pattern.
Note that the Super class in the factory method pattern can be an interface, abstract class, or normal class.
public class ConcretePersonA implements Person { private static final Logger LOGGER = LoggerFactory.getLogger(ConcretePersonA.class); public void run() { LOGGER.info("{} running",ConcretePersonA.class.getSimpleName()); } }
public class ConcretePersonB implements Person { private static final Logger LOGGER = LoggerFactory.getLogger(ConcretePersonB.class); public void run() { LOGGER.info("{} running",ConcretePersonB.class.getSimpleName()); } }
public class ConcretePersonC implements Person { private static final Logger LOGGER = LoggerFactory.getLogger(ConcretePersonC.class); public void run() { LOGGER.info("{} running", ConcretePersonC.class.getSimpleName()); } }
The Factory Class
Let’s define a Factory
class, which is a PersonFactory
class. As you can see from the code below, the PersonFactory
has a static getPerson
method that returns a Person
that depends on the type that has been provided.
public class PersonFactory { public static Person getPerson(String type) { if ("BaseRun".equals(type)) { return new ConcretePersonA(); } else if ("LongRun".equals(type) ) { return new ConcretePersonB(); } else if ("ProgressionRun".equals(type) ) { return new ConcretePersonC(); } return null; } }
Here, the signature of the factory method states that it will be returning a class of type Person
. The factory doesn’t say it’s returning a ConcretePersonA
, ConcretePersonB
, or ConcretePersonC
— it just says it’s returning something that implements the Person interface.
Running the Example
Now that we created a Person factory, the Person interface, and all the concrete persons that implement this interface. We will now create a “driver” program, FactoryPattern
, to test the Person factory.
public class FactoryPattern { public static void main( String[] args ) { Person person = PersonFactory.getPerson("BaseRun"); person.run(); person = PersonFactory.getPerson("LongRun"); person.run(); person = PersonFactory.getPerson("ProgressionRun"); person.run(); } }
Here, we created an instance of each type of Person.
Conclusion
The main reason the factory pattern is used is that it introduces weak coupling instead of tight coupling, hiding concrete classes from the application. It provides customization hooks and the implementation comfortably accommodates new changes.
The factory must be used for a family of objects. If the classes doesn't extend a common base class or interface, they cannot be used in a factory design template.
The source code can be found in my GitHub repository .
In the next post, we will look at the Abstract Factory design pattern.
Recommend
-
56
Creational Design Patterns: Factory Pattern DZone's Guide to Creational Design Patterns: Factory Pattern As we continue to explore creational design patterns...
-
30
Creational Design Patterns: Prototype Pattern [Snippet] DZone's Guide to Creational Design Patterns: Prototype Pattern [Snippet] Want to learn more about usi...
-
50
This article explores the Factory Method design pattern and its implementation in Python. Design patterns became a popular topic in late 90s after the so-called Gang of Four (GoF: Gamma, Helm, Johson, and Vlissides) publ...
-
22
When you need to ensure only a single instance of a class is created, and you want to provide a global point of access to it, the Singleton design pattern can be of great help. Examples of typical singletons include an ap...
-
8
Constructor PatternIn the constructor pattern, instead of returning the instance from the function, we use the new operator along with the function name.0 reactionsfunction createFruit(name) {...
-
13
Reading Time: 3 minutes Overview In this article, I will be sharing the working of a singleton pattern, in a nutshell, using a simple real-world example. 1. Singleton Design Pattern The aim of the singleto...
-
9
Understanding Factory Method with a Factory Design Pattern Case Study In our previous blog post, we looked at software design patterns and the various benefits of using them. In this blog post, we delve deeper into the factory design...
-
4
The Easy Method To Factory Reset Your Xbox Series X Or S ...
-
8
The Factory Method Pattern explained with a REAL example ...
-
6
Factory Method Pattern 工厂方法模式简介与 C# 示例【创建型】【设计模式来了】 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK