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.
01.
package
com.ddlab.rnd.patterns;
02.
03.
04.
05.
06.
public
interface
Roles
07.
{
08.
public
String getRole();
09.
}
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.
01.
package
com.ddlab.rnd.patterns;
02.
03.
04.
05.
06.
public
class
CEORoles
implements
Roles
07.
{
08.
public
String getRole()
09.
{
10.
return
"CEO is the supreme head of the company"
;
11.
}
12.
}
13.
14.
package
com.ddlab.rnd.patterns;
15.
16.
17.
18.
19.
public
class
CFORoles
implements
Roles
20.
{
21.
@Override
22.
public
String getRole()
23.
{
24.
return
"CFO is the finance head of a company"
;
25.
}
26.
}
27.
28.
package
com.ddlab.rnd.patterns;
29.
30.
31.
32.
33.
public
class
CTORoles
implements
Roles
34.
{
35.
@Override
36.
public
String getRole()
37.
{
38.
return
"CTO is the technology decision maker of a company"
;
39.
}
40.
}
Now we have to think about the Factory from where we generate the Object dynamically. Let us see the code below.
01.
package
com.ddlab.rnd.patterns;
02.
03.
04.
05.
06.
public
abstract
class
EmployeeFactory
07.
{
08.
public
static
Roles getRole( String type )
09.
{
10.
Roles roles =
null
;
11.
if
( type.equals(
"cfo"
))
12.
roles =
new
CFORoles();
13.
else
if
( type.equals(
"cto"
))
14.
roles =
new
CTORoles();
15.
else
if
( type.equals(
"ceo"
))
16.
roles =
new
CEORoles();
17.
return
roles;
18.
}
19.
}
Now let us write a simple harness class as a test to verify the design.
01.
package
com.ddlab.rnd.patterns;
02.
03.
04.
05.
06.
public
class
TestTraditionalFactoryDesign
07.
{
08.
public
static
void
main(String[] args)
09.
{
10.
String type =
"ceo"
;
11.
long
startTime = System.nanoTime();
12.
String role = EmployeeFactory.getRole(type).getRole();
13.
System.out.println(
"Role ::: "
+role);
14.
long
endTime = System.nanoTime();
15.
System.out.println(
"Time difference ::: "
+(endTime-startTime)+
" nano seconds"
);
16.
}
17.
18.
}
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:
01.
package
com.ddlab.rnd.patterns;
02.
03.
04.
05.
06.
public
enum
EmployeeType
07.
{
08.
CEO(
"CEO"
)
09.
{
10.
@Override
11.
public
Roles getRoles()
12.
{
13.
return
new
CEORoles();
14.
}
15.
},
16.
17.
CTO(
"CTO"
)
18.
{
19.
@Override
20.
public
Roles getRoles() {
21.
22.
return
new
CTORoles();
23.
}
24.
},
25.
26.
CFO(
"CFO"
)
27.
{
28.
@Override
29.
public
Roles getRoles() {
30.
31.
return
new
CFORoles();
32.
}
33.
};
34.
35.
private
EmployeeType( String type )
36.
{
37.
this
.type = type;
38.
}
39.
40.
private
String type;
41.
public
abstract
Roles getRoles();
42.
43.
public
String getType()
44.
{
45.
return
type;
46.
}
47.
48.
@Override
49.
public
String toString()
50.
{
51.
return
"TYPE CODE -> "
+type;
52.
}
53.
}
The harness class we've tested is shown below:
01.
package
com.ddlab.rnd.patterns;
02.
import
java.util.HashMap;
03.
import
java.util.Map;
04.
05.
06.
07.
08.
public
class
TestFactoryDesign
09.
{
10.
static
Map typeMap =
new
HashMap();
11.
12.
static
13.
{
14.
typeMap.put(
"cto"
, EmployeeType.CTO);
15.
typeMap.put(
"ceo"
, EmployeeType.CEO);
16.
typeMap.put(
"cfo"
, EmployeeType.CFO);
17.
}
18.
19.
public
static
void
main(String[] args)
20.
{
21.
String empType =
"ceo"
;
22.
try
23.
{
24.
long
startTime = System.nanoTime();
25.
String whatIstheRole = typeMap.get(empType).getRoles().getRole();
26.
System.out.println(
"Role of the Employee :::"
+whatIstheRole);
27.
long
endTime = System.nanoTime();
28.
System.out.println(
"Time difference ::: "
+(endTime-startTime)+
" nano seconds"
);
29.
}
30.
catch
(NullPointerException e)
31.
{
32.
System.out.println(
"No such Role is found"
);
33.
e.printStackTrace();
34.
}
35.
}
36.
}
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.