Showing posts with label Factory Pattern. Show all posts
Showing posts with label Factory Pattern. Show all posts

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

Sunday, 22 September 2013

Factory Design Pattern - Key Points

Master Software Architecture!

Subscribe to Ram N Java for clean code, design pattern breakdowns, and easy-to-follow Java tutorials!

SUBSCRIBE NOW

What is the Factory Design Pattern?

The Factory Design Pattern is a foundational creational pattern in object-oriented programming. Instead of using the new operator directly in client classes to instantiate concrete objects, the creation logic is delegated to a specialized factory class or method.

This design creates a clean separation of concerns, ensuring that client applications depend purely on interfaces or abstract classes rather than concrete implementations.

Essential Key Points to Remember

  • Loose Coupling: Decouples the client classes from the specific concrete classes they instantiate. Changes to concrete classes do not ripple through client code.
  • Single Responsibility Principle: Consolidates object creation rules, initialization, and validation into one dedicated location.
  • Open/Closed Principle: Adding a new implementation requires minimal updates inside the factory, leaving existing client logic untouched and closed for modification.
  • Encapsulated Creation Logic: If instantiating an object involves complex configuration or environment-dependent setup, the factory encapsulates those details neatly.
  • Coding to Interfaces: Clients work directly against common interfaces, allowing seamless swapping of implementations at runtime.

When Should You Apply It?

The Factory Pattern is ideal when:

  • A class cannot anticipate the exact sub-classes of objects it must create.
  • You want to centralize object creation to make future refactoring and unit testing easier.
  • You want to provide a library or framework where users can extend internal components without exposing concrete construction logic.

Watch More Related Design Pattern Tutorials


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

Saturday, 21 September 2013

Factory Design Pattern - Introduction

Master Software Architecture!

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 a cornerstone of creational design patterns. In standard object-oriented programming, calling constructors directly with the new keyword tightly couples your application logic to concrete implementations.

The Factory Pattern solves this by delegating the responsibility of object instantiation to a specialized factory class. As a result, client code interacts only with shared interfaces, making applications modular, testable, and easier to scale.

Core Structural Components

  • Product Interface: Defines the common contract or behavioral methods that all concrete objects must fulfill.
  • Concrete Products: The actual classes implementing the product interface with domain-specific logic.
  • Creator / Factory Class: Contains the factory method that inspects inputs or configuration settings and decides which concrete product instance to return.
  • Client: Requests product instances through the factory without knowing or managing the concrete class names directly.

Key Benefits for Software Engineers

  • Loose Coupling: Eliminates hardcoded dependencies between client business logic and concrete classes.
  • Single Responsibility Principle: Gathers complex creation, setup, and initialization logic into one central location.
  • Open/Closed Principle: You can introduce new product variations without altering the existing code that consumes them.

Watch More Related Design Pattern Tutorials


Click the below Image to Enlarge
Factory Design Pattern - Introduction

Tutorials