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."
Join the DZone community and get the full member experience.
Join For FreeIntroduction
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.
Opinions expressed by DZone contributors are their own.
Comments