Junior — Middle
What is the main purpose 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 specifying the exact class of the object being created. Its main purpose is to encapsulate the logic of object creation, allowing client code to work with abstractions rather than concrete implementations. This makes it easier to extend and maintain the code, as adding new object types does not require changing the client code, just extending the factory.
Example in PHP:
interface Product {
public function getName();
}
class ConcreteProductA implements Product {
public function getName() {
return "Product A";
}
}
class ConcreteProductB implements Product {
public function getName() {
return "Product B";
}
}
class Factory {
public static function createProduct(string $type): Product {
if ($type === 'A') {
return new ConcreteProductA();
} elseif ($type === 'B') {
return new ConcreteProductB();
}
throw new Exception("Unknown product type");
}
}
// Usage
$product = Factory::createProduct('A');
echo $product->getName(); // Product A