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

相关内容

热门资讯

透视苹果版!微乐小程序授权,七... 透视苹果版!微乐小程序授权,七彩捞腌菜神器下载,详细教程!(有挂透明挂)-哔哩哔哩;无需打开直接搜索...
实操分享"指尖四川辅... 实操分享"指尖四川辅助脚本"开挂(透视)辅助下载(一直确实是有挂)-哔哩哔哩;指尖四川辅助脚本简单的...
一分钟了解"赣牌圈总... 一分钟了解"赣牌圈总输"开挂(透视)辅助安装(原来是有挂)-哔哩哔哩;是一款可以让一直输的玩家,快速...
分享个大家!玫瑰大厅辅助,樱花... 分享个大家!玫瑰大厅辅助,樱花之盛挂,存在挂教程(有挂讲解)-哔哩哔哩>>您好:软件加薇136704...
推荐十款"非凡贪玩挂... 推荐十款"非凡贪玩挂"开挂(透视)辅助安装(果然真的有挂的)-哔哩哔哩;非凡贪玩挂是一款益智类棋牌手...
重磅来袭!途游手游辅助,约局吧... 重磅来袭!途游手游辅助,约局吧开挂,教你教程(有挂方略)-哔哩哔哩>>您好:软件加薇13670430...
透视攻略"欢乐情怀辅... 透视攻略"欢乐情怀辅助挂"开挂(透视)辅助脚本(一贯确实是有挂的)-哔哩哔哩;AI辅助机器人普及解说...
科技介绍!免费的衢州都莱辅助器... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
透视脚本"悟空大厅免... 透视脚本"悟空大厅免费辅助器"开挂(透视)辅助平台(一直确实是有挂)-哔哩哔哩;悟空大厅免费辅助器是...
记者揭秘!微乐手游微乐辅助免费... 记者揭秘!微乐手游微乐辅助免费,斗棋辅助脚本视频,必备教程(有人有挂)-哔哩哔哩 >>您好:软件加薇...