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

相关内容

热门资讯

透视了解"拱趴大菠萝... 透视了解"拱趴大菠萝十三水作弊"详细辅助必备教程(本然真的是有挂)1、很好的工具软件,可以解锁游戏的...
透视真的"如何下载w... 1、透视真的"如何下载wepoker安装包"详细辅助微扑克教程(切实存在有挂)(UU poker、如...
透视透视"wepok... 透视透视"wepoker软件安装包"详细辅助安装教程(起初真的是有挂);wepoker软件安装包软件...
透视数据"epoke... 您好,epoker底牌透视这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
透视私人局"hhpo... 透视私人局"hhpoker是内部控制吗"详细辅助安装教程(真是存在有挂);人气非常高,ai更新快且高...
透视真的"xpoke... 透视真的"xpoker辅助工具"详细辅助德州教程(固有真的有挂)1、玩家可以在xpoker辅助工具软...
透视了解"hh po... 透视了解"hh poker软件"详细辅助揭秘教程(一直是真的有挂)1、不需要AI权限,帮助你快速的进...
透视智能ai"soh... 《透视智能ai"sohoo辅助"详细辅助力荐教程(确实真的有挂)》 sohoo辅助软件透明挂更新公告...
透视辅助"wepok... 透视辅助"wepoker辅助脚本"详细辅助实用技巧(起初是真的有挂);亲真的是有正版授权,小编(透视...
透视挂透视"约局吧德... 此外,数据分析德州(约局吧德州有挂吗)辅助神器app还具备辅助透视行为开挂功能,通过对客户约局吧德州...