Junior — Middle
What is the main purpose of the Factory pattern in software development?
sobes.tech AI
Answer from AI
The Factory pattern is designed to create objects without the need to specify the exact class of the object being created in the client code. This allows:
- Encapsulating the logic of object creation.
- Simplifying the replacement and extension of the types of objects created.
- Increasing the flexibility and maintainability of the code.
For example, instead of directly calling a constructor, the client calls a factory method that returns the required object based on parameters or configuration.
Example in pseudocode:
interface Product {}
class ConcreteProductA implements Product {}
class ConcreteProductB implements Product {}
class Factory {
public static Product createProduct(String type) {
if (type.equals("A")) return new ConcreteProductA();
else if (type.equals("B")) return new ConcreteProductB();
else throw new IllegalArgumentException("Unknown type");
}
}
// Usage:
Product product = Factory.createProduct("A");