目的
在不指定具体类的情况下创建一系列相关或依赖对象。 通常创建的类都实现相同的接口。 抽象工厂的客户并不关心这些对象是如何创建的,它只是知道它们是如何一起运行的。
UML 图
![](https://img.haomeiwen.com/i19693210/7a8d172c01c5b554.png)
★官方PHP高级学习交流社群「点击」管理整理了一些资料,BAT等一线大厂进阶知识体系备好(相关学习资料以及笔面试题)以及不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货
代码
- Product.php
<?php
namespace DesignPatterns\Creational\AbstractFactory;
interface Product
{
public function calculatePrice(): int;
}
- ShippableProduct.php
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class ShippableProduct implements Product
{
/**
* @var float
*/
private $productPrice;
/**
* @var float
*/
private $shippingCosts;
public function __construct(int $productPrice, int $shippingCosts)
{
$this->productPrice = $productPrice;
$this->shippingCosts = $shippingCosts;
}
public function calculatePrice(): int
{
return $this->productPrice + $this->shippingCosts;
}
}
- DigitalProduct.php
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class DigitalProduct implements Product
{
/**
* @var int
*/
private $price;
public function __construct(int $price)
{
$this->price = $price;
}
public function calculatePrice(): int
{
return $this->price;
}
}
- ProductFactory.php
<?php
namespace DesignPatterns\Creational\AbstractFactory;
class ProductFactory
{
const SHIPPING_COSTS = 50;
public function createShippableProduct(int $price): Product
{
return new ShippableProduct($price, self::SHIPPING_COSTS);
}
public function createDigitalProduct(int $price): Product
{
return new DigitalProduct($price);
}
}
Test
Tests/AbstractFactoryTest.php
<?php
namespace DesignPatterns\Creational\AbstractFactory\Tests;
use DesignPatterns\Creational\AbstractFactory\DigitalProduct;
use DesignPatterns\Creational\AbstractFactory\ProductFactory;
use DesignPatterns\Creational\AbstractFactory\ShippableProduct;
use PHPUnit\Framework\TestCase;
class AbstractFactoryTest extends TestCase
{
public function testCanCreateDigitalProduct()
{
$factory = new ProductFactory();
$product = $factory->createDigitalProduct(150);
$this->assertInstanceOf(DigitalProduct::class, $product);
}
public function testCanCreateShippableProduct()
{
$factory = new ProductFactory();
$product = $factory->createShippableProduct(150);
$this->assertInstanceOf(ShippableProduct::class, $product);
}
public function testCanCalculatePriceForDigitalProduct()
{
$factory = new ProductFactory();
$product = $factory->createDigitalProduct(150);
$this->assertEquals(150, $product->calculatePrice());
}
public function testCanCalculatePriceForShippableProduct()
{
$factory = new ProductFactory();
$product = $factory->createShippableProduct(150);
$this->assertEquals(200, $product->calculatePrice());
}
}
PHP 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)
面试10家公司,收获9个offer,2020年PHP 面试问题
★如果喜欢我的文章,想与更多资深开发者一起交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入我们的群-点击此处(群号码856460874)。
![](https://img.haomeiwen.com/i19693210/9f11e402acc9832b.png)
内容不错的话希望大家支持鼓励下点个赞/喜欢,欢迎一起来交流;另外如果有什么问题 建议 想看的内容可以在评论提出
网友评论