I am back with a new blog post titled “Factory Pattern Approach in Java”. Recently I was developing pricing strategies for my web application and during the development I learnt that how factory pattern can be useful and efficient for such type of functionality. Factory pattern is a quite common design pattern used in Java. Using this approach, we create object without exposing the underlying logic and refer to newly created object using a common interface.
Let me illustrate it with an example:
In this example, we’ll create a “Blackhole factory” that will return different types of blackhole. For instance, we might tell our factory that we want a stellar blackhole, or a supermassive blackhole, and the Blackhole factory will give us a blackhole of the type that we want.(The reason why I took blackhole as an example is because I am quite fascinated by it 😉 )
Interface
We will create a Blackhole interface. Any blackhole that our factory returns should implement the Blackhole interface. We’ll just specify that any class that claims itself a Blackhole must implement a swallow() method that looks like this(Blackhole’s gravitational pull is so strong that it can swallow almost anything 😛 ) :
interface Blackhole { public void swallow(); }
Classes implementing the interface
Now, we’ll write a few classes that implement our Blackhole interface. Each class implements the swallow() method, but each class has its own implementation.
class Centaurus implements Blackhole { public void swallow() { System.out.println("I can swallow moon"); } }
class Fornax implements Blackhole { public void swallow() { System.out.println("I can swallow Earth"); } }
class Andromeda implements Blackhole { public void swallow() { System.out.println("I can swallow massive stars"); } }
Factory class
Now let us define our factory class BlackholeFactory class.The BlackholeFactory class has a static getBlackHole method that returns a “BlackHole” depending on the criteria specified.
class BlackholeFactory { public static BlackHole getBlackHole(String criteria) { if ( criteria.equals("stellar") ) return new Andromeda(); else if ( criteria.equals("supermassive") ) return new Fornax(); else if ( criteria.equals("miniature") ) return new Centaurus(); return null; } }
The factory getBlackHole() doesn’t reveal about the Blackhole it is going to return. It says it’s returning something that implements the Blackhole.
Driver Class
Now let us create a class that will fetch the object from the Factory:
public class FactoryPatternDriver { public static void main(String[] args) { // fetch a stellar Blackhole Blackhole blackHole = BlackholeFactory.getBlackHole("stellar"); blackHole.swallow(); // fetch a supermassive Blackhole blackHole = BlackholeFactory.getBlackHole("supermassive"); blackHole.swallow(); } }
The first swallow method call prints “I can swallow massive stars”. The second one prints “I can swallow Earth”.
I hope this example is clear 🙂
Recent Comments