不同对象类型的工厂对象
创始人
2025-01-08 23:00:25
0

使用抽象工厂模式,根据不同的条件返回不同的工厂对象。

实现代码如下:

// 定义一个抽象工厂接口
interface AbstractFactory {
   public function createProductA();
   public function createProductB();
}

// 实现具体工厂类
class ConcreteFactoryForType1 implements AbstractFactory {
   public function createProductA() {
      return new ProductType1A();
   }
   public function createProductB() {
      return new ProductType1B();
   }
}

class ConcreteFactoryForType2 implements AbstractFactory {
   public function createProductA() {
      return new ProductType2A();
   }
   public function createProductB() {
      return new ProductType2B();
   }
}

// 定义抽象产品接口
interface AbstractProductA {
   public function usefulFunctionA(): string;
}

interface AbstractProductB {
   public function usefulFunctionB(): string;
}

// 实现具体产品类
class ProductType1A implements AbstractProductA {
   public function usefulFunctionA(): string {
      return "The result of the product A1.";
   }
}

class ProductType1B implements AbstractProductB {
   public function usefulFunctionB(): string {
      return "The result of the product B1.";
   }
}

class ProductType2A implements AbstractProductA {
   public function usefulFunctionA(): string {
      return "The result of the product A2.";
   }
}

class ProductType2B implements AbstractProductB {
   public function usefulFunctionB(): string {
      return "The result of the product B2.";
   }
}

// 客户端代码,根据不同条件调用不同的工厂来获取不同类型的对象
$clientCode = function (AbstractFactory $factory) {
    $productA = $factory->createProductA();
    $productB = $factory->createProductB();

    echo $productA->usefulFunctionA() . "
"; echo $productB->usefulFunctionB() . "
"; }; // 调用客户端代码 $clientCode(new ConcreteFactoryForType1()); $clientCode(new ConcreteFactoryForType2());

相关内容

热门资讯

第9分钟开挂!九九山城万州辅助... 大家好,今天小编来为大家解答九九山城万州辅助这个问题咨询软件客服可以免费测试直接加微信(136704...
3分钟辅助!情怀辅助哪里可以装... 3分钟辅助!情怀辅助哪里可以装,哈糖大菠萝提高胜率(教程攻略开挂辅助下载),情怀辅助哪里可以装是用手...
第三分钟透视!手机暗宝辅助,哈... 第三分钟透视!手机暗宝辅助,哈糖大菠萝辅助(玩家必看科普开挂辅助软件) 了解更多开挂安装加(1367...
第8分钟辅助!wepoker底... 第8分钟辅助!wepoker底牌透视脚本,天天开心国王辅助(1.9分钟了解开挂辅助软件);致您一封信...
第1分钟开挂!蜀山挂件辅助,填... 第1分钟开挂!蜀山挂件辅助,填大坑辅助视频(透视辅助开挂辅助脚本);亲,填大坑辅助视频这款游戏原来确...
第4分钟辅助!wepoker辅... 《第4分钟辅助!wepoker辅助是真的假的,小程序微乐辅助器2.0(透视辅助开挂辅助下载)》 小程...
第二分钟透视!四川家园茶馆辅助... 【亲,四川家园茶馆辅助 这款游戏可以开挂的,确实是有挂的,很多玩家在这款四川家园茶馆辅助中打牌都会发...
9分钟辅助!金州水鱼天下源码,... 9分钟辅助!金州水鱼天下源码,微玩盒子网页游戏辅助(透视辅助开挂辅助安装);微玩盒子网页游戏辅助最新...
9分钟开挂!人海大厅挂什么好,... 9分钟开挂!人海大厅挂什么好,小闲川南宜宾辅助(透视黑科技开挂辅助工具) 【无需打开直接搜索加薇13...
4分钟辅助!掌中乐游戏中心辅助... 4分钟辅助!掌中乐游戏中心辅助器,新八戒怎么控制牌型(透视透视开挂辅助安装)相信很多朋友都在电脑上玩...