Design Patterns

HarikaHarika
4 min read

What are Design Patterns ?

  • These are the reusable solutions for common software design problems.

  • These are like blueprints, can be customized to meet our needs.

Need of Design Patterns ?

  • Reusability of patterns

  • Helpful in fixing performance and memory related issues

  • Standard solutions

  • Maintainability

  • Efficient way of solving problems

  • Less complexity

  • Less Redundancy

  • Can refactor our code easily

Classification of Design Patterns :

Design Patterns are of mainly three types :

  1. Creational Patterns

  2. Structural Patterns

  3. Behavioral Patterns

1.Creational Patterns

Creational Patterns are used in object creation, which increases the flexibility to reuse the existing code. It manages the entire process of creation of objects, by hiding the complexity.

It decouples the client code from concrete classes meaning, these patterns hide the exact class names and creation logic from client code, so the client doesn’t care which class is actually being created, it just uses the object.

Types of Creational Patterns:

  1. Factory Method

  2. Abstract Factory Method

  3. Builder Method

  4. Prototype Method

  5. Singleton Method

Factory Method

The Factory Method is a creational pattern that defines a way to create objects in the superclass but lets subclasses decide which specific type of object to instantiate. It encapsulates the object creation logic, decoupling it from the client code that uses the objects. Also, the super class in Factory pattern can be an interface, or an abstract class, or a Java class.

When to use ?

  • When you don’t know which class you want to create.

  • When you want to delegate the responsibility of object creation to subclasses.

  • When you want to follow Open/Closed principle, meaning classes should be open for extension and closed for modification.

  • When you need flexibility in object creation.

For Example

Let's say you are designing an application for a manufacturing company that initially produced only Televisions. Your code was initially handling the production and details of TVs, with the core logic of Television class. But later, the company expanded and started manufacturing other appliances like Air Conditioners (ACs), Refrigerators, and Washing Machines.

Now you need your application to support these new products too.
However, directly adding all of them into your existing code would make it more complex and would require major changes to the codebase; which is not a good practice! Here comes our Factory Method !

How ?

The Factory Method avoids direct object creation. Instead of your code manually creating objects like new Television(), new AC(), etc., you delegate the creation to a Factory.

The Factory decides which appliance object to create based on the requirement, without changing the core application logic.

How to implement :

Create a common interface or abstract class, such as Appliance, with methods like produce(), price(), and details().

  • Each product (Television, AC, Refrigerator, Washing Machine) implements the Appliance interface.

  • The Factory will have methods that return the appropriate appliance object based on the input.

  • Your application simply calls the Factory without worrying about which product is actually created.

  • Each method (produce(), price(), details()) can have different implementations in the respective subclasses.

// Appliance.java
public interface Appliance {
    void produce();
    double price();
    void details();
}


// Television.java
public class Television implements Appliance {
    @Override
    public void produce() {
        System.out.println("Producing a Television...");
    }

    @Override
    public double price() {
        return 50000.0;
    }

    @Override
    public void details() {
        System.out.println("Television: 55-inch 4K LED");
    }
}

// AC.java
public class AC implements Appliance {
    @Override
    public void produce() {
        System.out.println("Producing an Air Conditioner...");
    }

    @Override
    public double price() {
        return 70000.0;
    }

    @Override
    public void details() {
        System.out.println("AC: 1.5 Ton Inverter AC");
    }
}

// WashingMachine.java
public class WashingMachine implements Appliance {
    @Override
    public void produce() {
        System.out.println("Producing a Washing Machine...");
    }

    @Override
    public double price() {
        return 40000.0;
    }

    @Override
    public void details() {
        System.out.println("Washing Machine: Front Load with 8kg capacity");
    }
}
// and soon..

// ApplianceFactory.java
public class ApplianceFactory {
    public static Appliance getAppliance(String type) {
        if (type == null) {
            return null;
        }
        switch (type.toLowerCase()) {
            case "television":
                return new Television();
            case "ac":
                return new AC();
            case "refrigerator":
                return new Refrigerator();
            case "washingmachine":
                return new WashingMachine();
            default:
                throw new IllegalArgumentException("Unknown appliance type: " + type);
        }
    }
}

//client code
// Main.java
public class Main {
    public static void main(String[] args) {
        Appliance tv = ApplianceFactory.getAppliance("television");
        tv.produce();
        tv.details();
        System.out.println("Price: $" + tv.price());

        System.out.println("-----------------------------");

        Appliance ac = ApplianceFactory.getAppliance("ac");
        ac.produce();
        ac.details();
        System.out.println("Price: $" + ac.price());
    }
}

By using the Factory Method pattern:
- We keep client code decoupled from different appliances types.
- Adding new appliance is easy.
- Creation logic is encapsulated in factory classes, promoting maintainability and readability.

0
Subscribe to my newsletter

Read articles from Harika directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harika
Harika