1.3. Factory Method
For simple cases, this abstract class could be just an interface.
This pattern is a “real” Design Pattern because it achieves theDependency Inversion principle a.k.a the “D” in SOLID principles.
It means the FactoryMethod class depends on abstractions, not concreteclasses. This is the real trick compared to SimpleFactory orStaticFactory.
You can also find this code on GitHub
Logger.php
StdoutLogger.php
- <?php
- namespace DesignPatterns\Creational\FactoryMethod;
- class StdoutLogger implements Logger
- {
- public function log(string $message)
- {
- echo $message;
- }
LoggerFactory.php
- <?php
- namespace DesignPatterns\Creational\FactoryMethod;
- interface LoggerFactory
- {
- public function createLogger(): Logger;
- }
StdoutLoggerFactory.php
FileLoggerFactory.php
- <?php
- namespace DesignPatterns\Creational\FactoryMethod;
- class FileLoggerFactory implements LoggerFactory
- {
- * @var string
- */
- private $filePath;
- public function __construct(string $filePath)
- {
- $this->filePath = $filePath;
- }
- public function createLogger(): Logger
- {
- return new FileLogger($this->filePath);
- }
- }