Friday, 27 September 2013

Factory Design Pattern - Implementation

Level Up Your Java Skills!

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

SUBSCRIBE NOW

What is the Factory Design Pattern?

The Factory Design Pattern is one of the most widely used creational patterns in Java. It defines an interface or abstract class for creating an object, but allows subclasses or factory methods to decide which specific class to instantiate.

By delegating object creation to a centralized factory, your application decouples client business logic from concrete implementation details, making your codebase significantly more flexible and maintainable.

Complete Java Code Implementation

Below is a clear, beginner-friendly example implementing the Factory Pattern with shapes:

// 1. Common Interface
interface Shape {
    void draw();
}

// 2. Concrete Implementations
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Circle.");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle.");
    }
}

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

// 3. Shape Factory
class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null || shapeType.trim().isEmpty()) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

// 4. Client / Driver Application
public class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();

        Shape shape1 = factory.getShape("CIRCLE");
        if (shape1 != null) {
            shape1.draw();
        }

        Shape shape2 = factory.getShape("RECTANGLE");
        if (shape2 != null) {
            shape2.draw();
        }

        Shape shape3 = factory.getShape("SQUARE");
        if (shape3 != null) {
            shape3.draw();
        }
    }
}

Key Best Practices

  • Code to Interfaces: The client program should interact exclusively through the interface type rather than concrete classes.
  • Centralize Instantiation: Keep creation logic encapsulated inside factory methods so modifications do not impact client code.
  • Support Extensibility: Introducing new implementations is seamless and only requires updating the factory logic.

Watch More Related Design Pattern Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=q9p-E19JFlA

Click the below Image to Enlarge
Factory Design Pattern - Implementation - Class Diagram























Animal.java

public interface Animal
{
public String speak();
}


Dog .java

public class Dog implements Animal
{

@Override
public String speak()
{
return "Bark Bark Bark";
}

}


Duck.java

public class Duck implements Animal
{

@Override
public String speak()
{
return "Quack Quack Quack";
}

}

Lion.java

public class Lion implements Animal
{

@Override
public String speak()
{
return "Roar";
}

}

AnimalFactory.java

public class AnimalFactory
{
public Animal getAnimal( String animalType )
{
Animal animal = null;
if( "dog".equals(animalType) )
{
animal = new Dog();
}
else if( "duck".equals(animalType) )
{
animal = new Duck();
}
else if( "lion".equals(animalType) )
{
animal = new Lion();
}
return animal;
}
}


Client.java

public class Client
{

public static void main( String[] args )
{
AnimalFactory animalFactory = new AnimalFactory();
Animal animal = null;
String speakSound = null;
animal = animalFactory.getAnimal("dog");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("dog speak : "+speakSound);
System.out.println();

animal = animalFactory.getAnimal("duck");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("duck speak : "+speakSound);
System.out.println();

animal = animalFactory.getAnimal("lion");
System.out.println("Animal Type : "+animal.getClass().getName());
speakSound = animal.speak();

System.out.println("lion speak : "+speakSound);

}

}

Output

Animal Type : Dog
dog speak : Bark Bark Bark

Animal Type : Duck
duck speak : Quack Quack Quack

Animal Type : Lion
lion speak : Roar

No comments:

Post a Comment

Tutorials