Abstract factory code examples of PHP design patterns (3)



The advantage over the simple factory pattern is that you can create an object by subclassing it in different ways.

For a simple example, this abstract class might just be an interface.

This pattern is a “real” design pattern because it realizes the “dependency inversion” of “d” in the s.o.l.i.d principle.

This means that the factory method pattern depends on the abstract class, not the concrete class. This is an advantage over simple factory mode and static factory mode.

UML diagram

Official PHP advanced learning exchange community “click”The management has sorted out some materials, bat and other advanced knowledge systems are ready (relevant learning materials and written questions), and not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, tp6, laravel, yii2, redis, spool, swoft, Kafka, MySQL optimization, shell script, docker, microservice, nginx and other advanced knowledge points Advanced dry goods


  • Logger.php
  • StdoutLogger.php
  • FileLogger.php
filePath = $filePath;
    public function log(string $message)
        file_put_contents($this->filePath, $message . PHP_EOL, FILE_APPEND);
  • LoggerFactory.php
  • StdoutLoggerFactory.php
  • FileLoggerFactory.php
filePath = $filePath;
    public function createLogger(): Logger
        return new FileLogger($this->filePath);


  • Tests/FactoryMethodTest.php
        $this->assertInstanceOf(StdoutLogger::class, $logger);
    public function testCanCreateFileLogging()
        $loggerFactory = new FileLoggerFactory(sys_get_temp_dir());
        $logger = $loggerFactory->createLogger();
        $this->assertInstanceOf(FileLogger::class, $logger);

PHP Internet architect’s growth path * “design patterns” Ultimate Guide

PHP Internet architect 50K growth Guide + general outline of industry problem solving (continuous update)

Interview 10 companies, get 9 offers, PHP interview questions in 2020

If you like my article and want to exchange and study with more senior developers, you can get more technical consultation and guidance related to the interview of large factories. Welcome to join usOur group – click here(group number 856460874).

If the content is good, I hope you can support and encourage me to like it, and welcome to communicate with me. In addition, if you have any questions, please put forward the content you want to see in the comments