Junior — Middle
What is the main function of the Factory pattern in object-oriented programming?
sobes.tech AI
Answer from AI
The Factory pattern in object-oriented programming is designed to create objects without the need to specify the exact class of the object being created directly. Its main function is to encapsulate the logic of object creation, which allows:
- Eliminating tight coupling of code to specific classes.
- Simplifying the extension and maintenance of the code (for example, adding new types of objects).
- Centralizing object creation, which improves readability and manageability.
Example of a simple Factory 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();
else throw new IllegalArgumentException("Unknown animal type");
}
}
// Usage:
Animal animal = AnimalFactory.createAnimal("dog");
animal.speak(); // Outputs: Woof