Design Patterns — Factory Design Pattern Made EASY in Java

Rana M. Suleman
2 min readApr 4, 2021

The factory Design pattern is a type of Creational Design Pattern.

Let's take an example:

You have a drawing application, and the user selects the shape to draw.

At runtime, the class doesn't know what sub-classes will be required to execute the draw functionality of that shape.

To tackle this, this could be done!

public class Main {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();

if(input.equalsIgnoreCase("TRIANGLE")) {
new Triangle().draw();
}
if(input.equalsIgnoreCase("SQUARE")) {
new Square().draw();
}

}
}

This is known as Simple Factory.

But also here, you got yourself a tightly coupled code. If a new shape comes in the client code here, changes have be to made.

The idea behind Factory method Pattern is to create an interface for the creation of the objects, but the instantiation is left to its subclasses.

Let's see how we implement this:

public interface Shape {

public void draw();
}

The following classes implement the Shape interface.

public class Square implements Shape {
@Override
public void draw() {
System.out.print("Drawing Square");
}
}
public class Triangle implements Shape {
@Override
public void draw() {
System.out.print("Drawing Triangle");
}
}

Then we create a ShapeFactory.

public class ShapeFactory {

public Shape getShape(String shape) {

if(shape.equalsIgnoreCase("TRIANGLE")) {
return new Triangle();
}
if(shape.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}

The Client:

public class Main {

public static void main(String[] args) {

Shape shape;
ShapeFactory shapeFactory = new ShapeFactory();
Scanner input = new Scanner(System.in);

shape = shapeFactory.getShape(input.nextLine());
shape.draw();

}
}

For more: www.buffernest.com

--

--

Rana M. Suleman

Business oriented technology enthusiast, sharing ideas from the idea valley inside my immensely curious mind, A boring Software developer and a Gaming Nerd