当前位置: 首页 > 滚动 > >正文

PHP面向对象的设计模式-工厂模式(四) 全球今日讯

来源:腾讯云    时间:2023-04-28 22:10:48


(资料图片仅供参考)

产品族

产品族是一组相关的产品,例如不同品牌的汽车或电子设备。在抽象工厂模式中,每个具体工厂都将负责创建一个产品族的所有产品。下面是一个示例:

interface ProductAInterface {    public function getName();}class ProductA1 implements ProductAInterface {    public function getName() {        return "Product A1";    }}class ProductA2 implements ProductAInterface {    public function getName() {        return "Product A2";    }}interface ProductBInterface {    public function getName();}class ProductB1 implements ProductBInterface {    public function getName() {        return "Product B1";    }}class ProductB2 implements ProductBInterface {    public function getName() {        return "Product B2";    }}

在上面的代码中,我们定义了两个产品族:ProductA和ProductB。每个产品族都有两个具体产品:ProductA1和ProductA2,以及ProductB1和ProductB2。

使用抽象工厂模式

使用抽象工厂模式时,您需要首先选择要使用的具体工厂,然后使用该工厂来创建产品。下面是一个示例:

$factory1 = new ConcreteFactory1();$productA1 = $factory1->createProductA();echo $productA1->getName(); // Output: Product A1$factory2 = new ConcreteFactory2();$productB2 = $factory2->createProductB();echo $productB2->getName(); // Output: Product B2

在上面的代码中,我们首先创建了ConcreteFactory1和ConcreteFactory2的实例,然后使用它们来创建ProductA1和ProductB2的实例,并输出它们的名称。

X 关闭

推荐内容

最近更新

Copyright ©  2015-2022 华声服装网版权所有  备案号:京ICP备2021034106号-36   联系邮箱:55 16 53 8 @qq.com