Sobes.tech
Junior — Middle

Can you explain what is meant by the factory pattern in the context of software design?

sobes.tech AI

Answer from AI

The "Factory" pattern is a creational design pattern used to create objects without specifying the exact class of the object being created. Instead of directly calling the constructor, the client uses a factory method or class that decides which specific object to create.

This is useful when you want to separate the process of object creation from its usage, for example, to easily change the type of objects being created or to add new types without modifying the client code.

Example in Java:

interface Animal {
    void speak();
}

class Dog implements Animal {
    public void speak() {
        System.out.println("Woof");
    }
}

class Cat implements Animal {
    public void speak() {
        System.out.println("Meow");
    }
}

class AnimalFactory {
    public static Animal createAnimal(String type) {
        if ("dog".equalsIgnoreCase(type)) {
            return new Dog();
        } else if ("cat".equalsIgnoreCase(type)) {
            return new Cat();
        }
        throw new IllegalArgumentException("Unknown animal type");
    }
}

// Usage:
Animal animal = AnimalFactory.createAnimal("dog");
animal.speak(); // Outputs: Woof

Thus, the factory encapsulates the object creation logic and simplifies code extension and maintenance.