Middle
Что такое паттерн 'Фабрика' в контексте разработки на PHP?
sobes.tech AI
Answer from AI
The "Factory" pattern (Factory Method) is a creational design pattern that provides an interface for creating objects in a superclass but delegates the actual creation to subclasses. This allows subclasses to decide which class to instantiate.
Main components of the pattern:
- Product Interface/Abstract Class: Defines the interface for objects created by the factory method.
<?php // Product Interface interface Product { public function operation(): string; } - Concrete Products: Implement the product interface.
<?php // Concrete Product A class ConcreteProductA implements Product { public function operation(): string { return "Result of ConcreteProductA"; } } // Concrete Product B class ConcreteProductB implements Product { public function operation(): string { return "Result of ConcreteProductB"; } } - Creator Interface/Abstract Class: Declares the factory method, which returns a product object. It may also contain code that uses the product returned by the factory method.
<?php // Creator Abstract Class abstract class Creator { // The factory method itself abstract public function factoryMethod(): Product; // Some business logic that might use the product public function someOperation(): string { $product = $this->factoryMethod(); return "Creator: I've just worked with " . $product->operation(); } } - Concrete Creators: Override the factory method to return an instance of a specific product.
<?php // Concrete Creator A class ConcreteCreatorA extends Creator { public function factoryMethod(): Product { return new ConcreteProductA(); } } // Concrete Creator B class ConcreteCreatorB extends Creator { public function factoryMethod(): Product { return new ConcreteProductB(); } }
Working principle: Client code works with an abstract creator, calling its methods which, in turn, use the factory method to obtain an instance of the required product. The client does not know which specific product is created.
Advantages:
- Flexibility: Allows adding new product types without changing client code.
- Responsibility separation: Separates object creation code from code that uses these objects.
- Extensibility: Simplifies system extension with new object types.
Use cases:
- When a class cannot predict the type of objects it needs to create in advance.
- When subclasses should determine which objects to create.
- When it is necessary to provide the creation of related object families.
Example of usage:
<?php
// Client code
function clientCode(Creator $creator)
{
echo "Client: I'm not aware of the creator's class, but it still works.<br>\n"
. $creator->someOperation() . "<br>\n";
}
echo "App: Launched with the ConcreteCreatorA.<br>\n";
clientCode(new ConcreteCreatorA());
echo "<br>\n";
echo "App: Launched with the ConcreteCreatorB.<br>\n";
clientCode(new ConcreteCreatorB());