DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Factory Method Design Pattern
  • Abstract Factory Design Pattern
  • Strategy vs. Factory Design Patterns in Java
  • A Guide to Data-Driven Design and Architecture

Trending

  • Writing Reusable SQL Queries for Your Application With DbVisualizer Scripts
  • Navigating the Skies
  • Auto-Scaling DynamoDB Streams Applications on Kubernetes
  • Bad Software Examples: How Much Can Poor Code Hurt You?

Factory Design Pattern - An Effective Approach

As you might know, the Factory Method Pattern, popularly known as the Factory Design Pattern, is a design pattern categorized as a "Creational Design Pattern."

Debadatta Mishra user avatar by
Debadatta Mishra
·
Jul. 16, 12 · Tutorial
Like (1)
Save
Tweet
Share
55.39K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

As you might know, the Factory Method Pattern, popularly known as the Factory Design Pattern, is a design pattern categorized as a "Creational Design Pattern." The basic principle behind this pattern is that, at run time, we get an object of similar type based on the parameter we pass. You've probably seen many articles about this pattern. Developers produce it via different methods. Some are better than others. In this article, I will show you what I think is the best way of designing a Factory Design Pattern.

Technicalities

As said before, we will get a similar type of object at run-time in case of factory design so that underlying implementation of object will be behind the screen, let us consider a simple approach. Let us consider a Person object. This object can be either Male or Female. At run-time we should only consider the behavior, not the gender. By rules of the traditional approach, we create a Person interface and then two implementation classes like MalePerson and FemalePerson. Given the run-time gender data, we pass to a Factory method of a Factory class and decide whether the gender type is Male or Female. We then create the instance of the particular class and return the reference type object accordingly. This approach sounds good and we adopt it in many developmental activities. Can we ensure that it is the effective approach in fine-grained, multi-threaded applications, though? What about the performance ? Is there any other approach? Fortunately, the answer is yes.

Let us consider the real-time example of an organization where an employee can be a CEO, CTO, CFO, Developer, Test Engineer, HR, Personnel, Security, etc. If you want to know the role of an employee based on the organization, what will you do ? How will you create a better factory design so you can easily find the role without any performance penalty? Will you adopt the same traditional approach by providing multiple If clauses? You might argue that we should use the switch condition. Fine. Let's forge onward with the traditional approach and record the time it takes.

Let us employ our factory design in a traditional manner.

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public interface Roles 
{
public String getRole();
}

The above interface is used as a type. There can be various types of roles in the organization. One of its methods- "getRole()"- specifies the description of the role of the employee.

With this we can design the implementation classes for the suitable roles for CEO, CTO, and CFO in an organization.

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public class CEORoles implements Roles 
{
public String getRole() 
{
return "CEO is the supreme head of the company";
}
}

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public class CFORoles implements Roles
{
@Override
public String getRole() 
{
return "CFO is the finance head of a company";
}
}

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public class CTORoles implements Roles
{
@Override
public String getRole() 
{
return "CTO is the technology decision maker of a company";
}
}

Now we have to think about the Factory from where we generate the Object dynamically. Let us see the code below.

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public abstract class EmployeeFactory
{
public static Roles getRole( String type )
{
Roles roles = null;
if( type.equals("cfo"))
roles = new CFORoles();
else if( type.equals("cto"))
roles = new CTORoles();
else if( type.equals("ceo"))
roles = new CEORoles();
return roles;
}
}

Now let us write a simple harness class as a test to verify the design.

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public class TestTraditionalFactoryDesign 
{
public static void main(String[] args) 
{
String type = "ceo";
long startTime = System.nanoTime();
String role = EmployeeFactory.getRole(type).getRole();
System.out.println("Role ::: "+role);
long endTime = System.nanoTime();
System.out.println("Time difference ::: "+(endTime-startTime)+" nano seconds");
}

}

If you run the above program, the following is the output from my system (and just so you know, my system has 4 GB of RAM and an I5 processor):

Role ::: CEO is the supreme head of the company

Time difference ::: 3477574 nano seconds 

The above design seems to be correct, but what about performance? You may say it does not matter because it comes in terms of nano seconds. Sure, it doesn't matter, provided that your application is very small, but with large enterprise applications it's very important. If you are a good programmer or developer, you cannot ignore the performance issue, particularly in the case of product development where there may be similar products in the market.

To address the above issue, let us try another approach of factory design where there may be changes in the factory class.

Take a look at this next block of code below:

package com.ddlab.rnd.patterns;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public enum EmployeeType 
{
CEO("CEO") 
{
@Override
public Roles getRoles() 
{
return new CEORoles();
}
},

CTO("CTO")
{
@Override
public Roles getRoles() {

return new CTORoles();
}
},

CFO("CFO")
{
@Override
public Roles getRoles() {

return new CFORoles();
}
};

private EmployeeType( String type )
{
this.type = type;
}

private String type;
public abstract Roles getRoles();

public String getType() 
{
return type;
}

@Override
public String toString() 
{
return "TYPE CODE -> "+type;
}
}

 The harness class we've tested is shown below: 

package com.ddlab.rnd.patterns;
import java.util.HashMap;
import java.util.Map;
/**
 * @author Debadatta Mishra(PIKU)
 *
 */
public class TestFactoryDesign 
{
static Map typeMap = new HashMap();

static
{
typeMap.put("cto", EmployeeType.CTO);
typeMap.put("ceo", EmployeeType.CEO);
typeMap.put("cfo", EmployeeType.CFO);
}

public static void main(String[] args)
{
String empType = "ceo";
try 
{
long startTime = System.nanoTime();
String whatIstheRole = typeMap.get(empType).getRoles().getRole();
System.out.println("Role of the Employee :::"+whatIstheRole);
long endTime = System.nanoTime();
System.out.println("Time difference ::: "+(endTime-startTime)+" nano seconds");
}
catch (NullPointerException e) 
{
System.out.println("No such Role is found");
e.printStackTrace();
}
}
}

 If you run the above code, you will get the following output:

Role ::: CEO is the supreme head of the company

Time difference ::: 1049108 nano seconds

What about the time? Let's compare the time taken between the traditional approach and the modern approach. 

Traditional Approach:

3477574 nano seconds

Modern Approach(using enum and Map):

1049108 nano seconds


Can you think about the time difference? It's just about three times faster than the traditional approach.

Which is better then? Of course the modern approach of using enum is. Apart from enum, I have used Map to maintain the list of employee type and its corresponding enum. In this case, the If clause isn't needed, which may impact our performance as far as cyclomatic complexity is concerned. It is always better to use the above approach of 1049108 nano seconds. You can use ConcurrentMap for your multi-threaded application.

 Conclusion

So that's my article on factory design pattern. I hope you enjoyed it, and if you are confused at all, please contact me at debadatta.mishra@gmail.com.

 

Factory (object-oriented programming) Design

Opinions expressed by DZone contributors are their own.

Related

  • Factory Method Design Pattern
  • Abstract Factory Design Pattern
  • Strategy vs. Factory Design Patterns in Java
  • A Guide to Data-Driven Design and Architecture

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: