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

相关内容

热门资讯

2026版规律!微乐小程序黑科... 2026版规律!微乐小程序黑科技,手机微乐小程序破解器如何使用(透视)一贯有挂(哔哩哔哩)1、手机微...
第5分钟插件!微乐小程序免费黑... 第5分钟插件!微乐小程序免费黑科技,微乐河南麻将辅助ios(开挂)本来有挂(2026)1、微乐小程序...
透视辅助!微乐小程序黑科技,微... 透视辅助!微乐小程序黑科技,微信小程序微乐辅助器教程(透视)本来存在有挂(哔哩哔哩)1、游戏颠覆性的...
第五分钟插件!微乐小程序免费黑... 第五分钟插件!微乐小程序免费黑科技,微乐自建房辅助软件有哪些功能(开挂)本来有挂(2026)1、微乐...
透视透视!微乐小程序免费黑科技... 透视透视!微乐小程序免费黑科技,微乐陕西小程序破解器(透视)一贯真的有挂(哔哩哔哩)1、微乐陕西小程...
第二分钟安装!微乐小程序免费黑... 第二分钟安装!微乐小程序免费黑科技,微乐斗地主有挂吗(开挂)其实真的是有挂(2026)1、微乐小程序...
来临!微乐小程序黑科技,微乐小... 来临!微乐小程序黑科技,微乐小程序黑科技辅助工具2026最新推荐(透视)竟然是有挂(哔哩哔哩)1、玩...
9分钟开挂!微乐小程序免费黑科... 您好,微乐小程序免费黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
透视讲解!微乐小程序免费黑科技... 透视讲解!微乐小程序免费黑科技,微乐小程序修复系统有用吗(透视)果然真的有挂(哔哩哔哩)1、进入到微...
第4分钟安装!微乐小程序免费黑... 第4分钟安装!微乐小程序免费黑科技,微乐小程序辅助器代理(开挂)好像是有挂(2026)微乐小程序免费...