The simple factory pattern (Simple Factory) code examples of PHP design pattern (7)

purpose

The simple factory pattern is a simplified version of the factory pattern.

The biggest difference between it and the static factory model is that it is not "static". Because it is not static, you can have multiple factories with different parameters, and you can create subclasses for them. It can even be mocked, which is essential for writing testable code. This is why it is more popular than the static factory model!

UML graphics

Official PHP advanced learning exchange community "click" management to organize some materials, BAT and other first-line companies have advanced knowledge systems (relevant learning materials and written interview questions) and are not limited to: distributed architecture, high scalability, high Performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx and other knowledge points, advanced advanced dry goods

Code

  • SimpleFactory.php

<?php namespace DesignPatterns\Creational\SimpleFactory; class SimpleFactory { public function createBicycle(): Bicycle { return new Bicycle(); } }

  • Bicycle.php

<?php

namespace DesignPatterns\Creational\SimpleFactory;

class Bicycle
{
    public function driveTo(string $destination)
    {
        return $destination;
    }
}

usage


 $factory = new SimpleFactory();
 $bicycle = $factory->createBicycle();
 $bicycle->driveTo('Paris');

test

  • Tests/SimpleFactoryTest.php

<?php

namespace DesignPatterns\Creational\SimpleFactory\Tests;

use DesignPatterns\Creational\SimpleFactory\Bicycle;
use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
use PHPUnit\Framework\TestCase;

class SimpleFactoryTest extends TestCase
{
    public function testCanCreateBicycle()
    {
        $bicycle = (new SimpleFactory())->createBicycle();
        $this->assertInstanceOf(Bicycle::class, $bicycle);
    }
}

The Growth Path of PHP Internet Architect * The Ultimate Guide to "Design Patterns"

PHP Internet Architect 50K Growth Guide + Industry Problem Solving Guide (Continuous Update)

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

★If you like my article and want to communicate and learn with more senior developers, get more technical consultation and guidance related to interviews with big factories, welcome to join our group-click here (group number 856460874).

If the content is good, I hope everyone will support and encourage you to give a like/like, and welcome to communicate together; in addition, if you have any questions, you can suggest what you want to see in the comments.

Guess you like

Origin blog.csdn.net/weixin_43814458/article/details/108324376