Creational --- Simple Factory
Purpose:
It differs from the static factory because it is not static. Therefore, you can have multiple factories, differently parameterized, you can subclass it and you can mock it. It always should be preferred over a static factory!
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。SimpleFactory.php
<?php namespace DesignPatterns\Creational\SimpleFactory; class SimpleFactory { public function createBicycle(): Bicycle { return new Bicycle(); } }
Bicycle.php
<?php namespace DesignPattern\Creational\SimpleFactory; class Bicycle { public function driveTo($destination) { } }
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); } }

更多精彩