不同对象类型的工厂对象
创始人
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、不需要AI权...
一分钟揭秘"赣牌圈控... 一分钟揭秘"赣牌圈控制牌型"开挂(透视)德州私人局脚本(有人有挂);赣牌圈控制牌型是一种具有地方特色...
一分钟了解"乐乐围棋... 一分钟了解"乐乐围棋入门破解"开挂(透视)wepoker破解器有用吗(确实有挂);大家肯定在之前或者...
揭秘"微友破解器辅助... 揭秘"微友破解器辅助插件下载"开挂(透视)哈糖大菠萝有没有挂(真的有挂);最新软件透视开挂直接下载安...
教学盘点"人海大厅挂... 教学盘点"人海大厅挂什么好"开挂(透视)wepoker免费透视脚本(有挂详情);相信小伙伴都知道这个...
指导大家"八仙游戏辅... 指导大家"八仙游戏辅助"开挂(透视)wepoker辅助器如何使用(真的有挂);小薇(透视辅助)致您一...
透视软件"江西中至小... 透视软件"江西中至小程序黑科技"开挂(透视)wepoker破解器(有挂分析);江西中至小程序黑科技软...
透视代打"陕麻圈辅助... 透视代打"陕麻圈辅助器怎么安装"开挂(透视)hhpkoer辅助器视频(有挂解密);小薇(透视辅助)致...
热点讨论"丽水都莱辅... 【福星临门,好运相随】;热点讨论"丽水都莱辅助软件"开挂(透视)wepoker脚本(真的有挂);暗藏...
实测分享"老友福建麻... 实测分享"老友福建麻将辅助"开挂(透视)xpoker辅助控制(有挂详情);致您一封信;亲爱玩家:《透...