Java Design Pattern: Factory Method Pattern



Going on with the speach about design patterns started previously, we are going to talk about another pattern often used: the Factory Method Pattern.

The GoF (Gang of Four Design Patterns) defines it in this way:

It defines an interface to create objects, but leaves to the subclasses the decision about the type of the class to instantiate.

Starting from the definition, we can see that the problem regarding the inheritance among classes discussed for the Singleton Pattern is no longer present. In fact, we decide to use the Factory Method Pattern when we are not able to know the exact type of object to be created beforehand or when we want to delegate the task of creating objects to other entities

In the majority of the books about this topic, the pattern is represented using an UML diagram like the one below:

Factory Method Pattern

Foundamental patterns's entities

  • Creator:  it has the duty of declaring the Factory that will take care of returning the correct object;
  • ConcreteCreator: it makes the override of the Factory's method in order to return the correct implementation of the object;
  • Product: it defines the interface of the object that Factory has to return;
  • ConcreteProduct:it implements the object basing on Product;

The first observation, even if trivial, is that the implementation is definitely more complicated than the almost elementary one of the Singleton.

Some examples

Starting from an elementary example, let's define a CatFactory:

//Product
interface Cat{
public void speak ();
}

Every returned element from the factory has to implement this interface.

Let's create the concrete classes:

//ConcreteProduct
class Abissinian implements Cat{
public void speak(){
System.out.println("Abissinian");
}
}
class AmericanCurl implements Cat{
public void speak(){
System.out.println("American Curl");
}
}
class Asian implements Cat{
public void speak(){
System.out.println("Asian");
}
}

I decided to implement every class as non-public, assuming its placement in the same file. In fact, as we know, Java prohibits more than one public class in the same file, since the file must have the same name as the public class.

The foundamental concept of this pattern is the fact that every concrete class is a derivative of a basic type. In this case, every class implements Cat.

The Factory Class

The element to which the creation of objects is entrusted is precisely the so-called Factory class, which will have a static method with this functionality inside.

Let's see how this class could be implemented:

public class Factory{
public static Cat generateCat(String criteria){
if(criteria.equals("Abissino"))
return new Abissino();
if(criteria.equals("Curl"))
return new AmericanCurl();
if(criteria.equals("Asian"))
return new Asian();
return null;
}
}

We can notice that the code of the Factory class is quite easy, because it accepts only three strings. In a hypothetical real situation, the code would be longher and more complex, but this one is sufficient to give an idea of how the pattern works.

The Factory Method has different advantages and disadvantages, such as:

  • it represents a link to the subclasses: through the creator it is possible to dynamically choose which concrete class to use without any impact on the use of the end user;
  • it links class hierarchies in parallel: the ConcreteCreator can connect to the ConcreteProduct and generate a parallel link between different hierarchies;

Why use the Factory Method Pattern?

As I told before, there are different situations where we can't know before what the concrete type of the objects that will be instanciated. But the problem is much more bigger.

We could run into cases where we know the exact type of objects, but the latter may change in the future. So the client is free from the burden of knowing what kind of objects has to instanciate and the pattern returns an abstract object which is then realized through the classes inherited from the abstract entity. The client often guides the creation of the object, as in the example shown above, but ignores the details of its construction.

The Iterator pattern

It could sound strange, but the Iterator pattern can be assimilated to the Factory Method family. In fact Iterator allows us to access sequentially to the elements of a list, relieving the caller of the need to know what the instantiated classes are.

Iterator is an interface that exposes three methods:

  • boolean hasNext() that returns true if another iteration is possible;
  • Object next() which returns the item following the current one;
  • void remove() that removes the current element from the list;

Let's look at an example:

import java.io.*; 
import java.util.*; 
class Test { 
public static void main(String[] args) 
{ 
ArrayList
 list = new ArrayList
(); 
list.add("1"); 
list.add("2"); 
list.add("3"); 
list.add("4"); 
list.add("5"); 
// Iterator to scan the list  
Iterator iterator = list.iterator(); 
System.out.println("List elements : "); 
while (iterator.hasNext()) 
System.out.print(iterator.next() + " "); 
System.out.println(); 
} 
} 


We will obtain as output:

List elements : A B C D E

Java makes available a class called ListIterator that allows to scan objects collections in both directions, from the head to the tail and from the tail to the head.

Summing up

We use the Factory Method Pattern when:

  • A class can not know in advance the exact type of the object to create;
  • The class knows the exact type of objects, but it needs to delegate to another extern entity their creation;

Participants:

  • Product:  is the interface of the object created by the Factory Method;
  • ConcreteProduct: implements Product;
  • Creator: declares the Factory method and returns a Product object;
  • ConcreteCreator: specifies the Factory Method and returns the correct instance;

So:

  • The code has a higher flexibility level;
  • A wrong usage can lead to the generation of too much classes;

Focusing on some implementation details:

  • Creator can be concrete or abstract, and it can create a default version of the Factory Method;
  • A Factory can build objects of different types using if-then-else constructs;

Typically the Factory Method Pattern is used to create Logger and other softwares of this kind. wink

 
by Alessio Mungelli Date: 05-11-2019 java jdk jre explanation tutorial design pattern designpattern factory method factorymethod source code hits : 1570  
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

Graphic design and its impact on Web Development

In today's article we will explain the concept of graphic design, its fundamentals and what it brings into web development. Graphic design is applied to everything visual, believe or not,…

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Cross cultural challenges in web design, an overview

The user experience design of a product essentially lies between the intentions of the product and the characteristics of your user. - David Kadavy - The task of building a culturally appropriate…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration