不同对象类型的工厂对象
创始人
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());

相关内容

热门资讯

交流学习经验“微扑克有猫腻吗”... 微扑克有猫腻吗是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信...
一分钟揭秘“wepoker辅助... 您好:wepoker辅助工具好用吗这款游戏是可以开挂的,软件加【添加微信客服136704302】确实...
六分钟了解“微扑克辅助工具免费... 您好:微扑克辅助工具免费版的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
盘点十款“wepoker真的有... 盘点十款“wepoker真的有透视挂么”开挂辅助安装(透视)安装教程是一款可以让一直输的玩家,快速成...
发现一款“wepoker透视脚... 您好,wepoker透视脚本这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多...
玩家必看秘籍“wpk辅助是正规... 玩家必看秘籍“wpk辅助是正规平台吗”开挂辅助软件(透视)透明挂教程是一款可以让一直输的玩家,快速成...
发现一款“wpk开挂挂是真的吗... 您好:wpk开挂挂是真的吗的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
查到实测辅助“wepoker透... 无需打开直接搜索加微信客服(136704302)咨询了解wepoker透视挂的玩法辅助器目前(微信:...
技巧知识分享“wepoker如... 无需打开直接搜索加微信客服(136704302)咨询了解wepoker如何拿到好牌辅助器目前(微信:...
必知教程“wepoker透视开... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...