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

相关内容

热门资讯

透视插件!悦扑克脚本,aapo... 透视插件!悦扑克脚本,aapoker怎么选牌(透视)有挂教程(有挂头条)-哔哩哔哩1、aapoker...
据权威媒体报道!wepoker... 据权威媒体报道!wepoker手机插件,新超圣辅助器,技法教程(有挂秘诀)-哔哩哔哩1、完成wepo...
备受关注的!we poker插... 备受关注的!we poker插件,wepoker有透视底牌吗(透视)推荐教程(有挂解密)-哔哩哔哩1...
据统计!竹间茶馆透视码,wep... 据统计!竹间茶馆透视码,wepoker插件辅助,机巧教程(真的有挂)-哔哩哔哩1)竹间茶馆透视码辅助...
透视app!wepoker免费... 透视app!wepoker免费透视,德普之星辅助工具如何打开(透视)解谜教程(真的有挂)-哔哩哔哩德...
记者获悉!789大菠萝辅助,火... 记者获悉!789大菠萝辅助,火神大厅开挂,秘籍教程(真的有挂)-哔哩哔哩一、789大菠萝辅助可以开透...
最新消息!约局吧德州真的有透视... 最新消息!约局吧德州真的有透视挂吗,we-poker是什么软件(透视)推荐教程(有挂神器)-哔哩哔哩...
现场直击!欢聚水鱼智能辅助,人... 现场直击!欢聚水鱼智能辅助,人海大厅反杀,步骤教程(存在有挂)-哔哩哔哩1)欢聚水鱼智能辅助辅助插件...
透视了解!wpk透视工作室,w... 透视了解!wpk透视工作室,wepoker私人局怎么玩(透视)解密教程(有挂攻略)-哔哩哔哩1、操作...
一直以来!芒果辅助平台,雀神山... 一直以来!芒果辅助平台,雀神山庄麻将辅助器,法子教程(有挂规律)-哔哩哔哩1、每一步都需要思考,不同...