Thursday, May 17, 2012

Implementing Factory Design pattern using Type Safe Enum


When we have multiple similar type of objects and want to make such object creation process completely cohesive, we use factory design pattern.

There are two ways to implement it –
1.      Implementing the singleton factory class and then creating a method to generate the objects.
2.      Using type safe enum (in java) to create factory.

Here we will focus on second way of implementing factory design pattern.  There are following reasons to choose enum for factory implementation –
1.      Enum are inherently singleton.
2.      Enum can implement interface, which becomes the parent of each enum element.
3.      Enum provides easy way of avoiding code duplication by letting us develop common feature with same implementation in enum body and feature with different implementation in enum element body.
4.      Enum provides singleton implementation of each enum element.

Steps to implementing factory using enum–
Factory generates the similar type of objects. In other words all the objects generated by factory belongs to same super class/interface.

We can follow the below mentioned steps to generate factory -
1.      Develop an interface and declare the common features of the sub classes to it.
2.      Develop an enum, implementing the interface.
3.      Declare the enum properties adding specific implementation inside the body of enum element and common implementations inside enum.

Sample implementation –
Interface –
public interface Operation {
    double evaluate(double a, double b);

    String operationName();
}
Enum as factory –
public enum NumberOperation implements Operation {
    ADDIION("Addition") {
        public double evaluate(double a, double b) {
            return a + b;
        }
    },
    SUBSTRACTION("Substraction") {
        public double evaluate(double a, double b) {
            return a - b;
        }
    },
    MULTIPLICATION("Multiplication") {
        public double evaluate(double a, double b) {
            return a * b;
        }
    },
    DIVISION("Division") {
        public double evaluate(double a, double b) {
            if (b == 0)
                throw new IllegalArgumentException(String.format(
                        "%s is not supported as denominator for division", b));
            return a / b;
        }
    };

    private String operationName;

    private NumberOperation(String operationName) {
        this.operationName = operationName;
    }

    public String operationName() {
        return operationName;
    }
}
Limitations -
Enum can implement interface but can not extend abstract class. The workaround for it is to implement interface and develop common code in enum body. As we did in above mentioned example

Sample project –
The sample project with the above factory implementation can be downloaded from here.

In this project, we have developed a small requirement where client requirement was to provide implementation of addition, subtraction, multiplication and division.

During this design of sample program, we used TDD considering tests as our client and used below design patterns and design principals –
  1. Factory Design pattern
  2. Facade Design pattern
  3. Bridge Design pattern
  4. Strategy design pattern
  5. Singleton design patter (inherent in enum)
  6. Dependency inversion
  7. Cohesion
  8. TDD
To execute the project you will need maven 3 & java 5.0 or above installed in your application.  To check the program in execution use the following steps –
1-     Download and extract the zip
2-     Run mvn clean eclipse:eclipse test-compile
3-     Import the project into eclipse and execute NumberOperationSpec as JUnit.

2 comments:

  1. thanks for this information .
    you can find factory design pattern in simple and easy to understand language in a detail on
    http://www.itsoftpoint.com/?page_id=2666

    ReplyDelete
    Replies
    1. Hey Nasir,
      The link shared by you does not seem to be working now.

      Delete