首页 > 代码库 > AbstractFactory(抽象工厂模式)
AbstractFactory(抽象工厂模式)
AbstractFactory(抽象工厂模式)
有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象
<?php class Config { public static $factory = 1;} interface Product { public function getName();} abstract class AbstractFactory { public static function getFactory() { switch (Config::$factory) { case 1: return new FirstFactory(); case 2: return new SecondFactory(); } throw new Exception(‘Bad config‘); } abstract public function getProduct();} class FirstFactory extends AbstractFactory { public function getProduct() { return new FirstProduct(); }}class FirstProduct implements Product { public function getName() { return ‘The product from the first factory‘; }} class SecondFactory extends AbstractFactory { public function getProduct() { return new SecondProduct(); }}class SecondProduct implements Product { public function getName() { return ‘The product from second factory‘; }} $firstProduct = AbstractFactory::getFactory()->getProduct();Config::$factory = 2;$secondProduct = AbstractFactory::getFactory()->getProduct(); print_r($firstProduct->getName());// The first product from the first factoryprint_r($secondProduct->getName());// Second product from second factory
AbstractFactory(抽象工厂模式)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。