Factory Design Pattern in JAVA

The aim of the Factory pattern is to allow end user to define an interface for creating an object but let the subclasses decide which class to instantiate. In other words, Factory Method lets a class defer instantiation to the subclasses.

Example:

  1. Imagine an interface:

public interface Encoder {

public void encode();

}

 2.  Imagine the following subclasses: Each of the concrete classes implement the Encoder interface.

// Sub Class 1

public class StringEncoding implements Encoder {

public void encode() {

System.out.println(“Inside String Encoding”);

}

}

// Sub Class 2

public class DigitsEncoding implements Encoder {

public void encode() {

System.out.println(“Inside Digits Encoding”);

}

}

// Sub Class 3

public class HexDigitsEncoding implements Encoder {

public void encode() {

System.out.println(“Inside HexDigits Encoding”);

}

}

3. Java Factory Class:

public class EncodeFactory {

public static Encoder getEncoderClass(Integer value) {

if (value.equals(1)) {

return new StringEncoding();

} else if (value.equals(2)) {

return new DigitsEncoding();

} else if (value.equals(3)) {

return new HexDigitsEncoding();

}

return null;

}

}

4. Calling Program:

public class EncoderFactoryPatternDriver {

public static void main (String[] args) {

Encoder encodedClass = EncoderFactory.getEncoderClass(1);

encodedClass.encode() ;

}

}

Some information about Factory Pattern

  1. It’s desired to create a factory pattern when we need to have a single point of control for multiple products.
  2. The common parent class can be either abstract class or interface (shown in Point 1)
  3. A simple factory will return an instance of any of the several possible classes that have a common parent class. (shown in Point 3)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s