抽象工厂模式是一种创建型模式,它提供了一种创建一系列相关或相互依赖对象的最佳方式。在抽象工厂模式中,我们定义一个抽象工厂接口,由具体的工厂类来实现该接口,创建一系列相关的对象。
在 PHP 中,我们可以使用以下方式来实现抽象工厂模式:
<?php// 定义抽象产品类(汽车)abstract class Car{protected $brand;protected $type;public function __construct($brand, $type){$this->brand = $brand;$this->type = $type;}abstract public function run();}// 定义抽象产品类(手机)abstract class Phone{protected $brand;protected $model;public function __construct($brand, $model){$this->brand = $brand;$this->model = $model;}abstract public function call();}<?php// 定义具体产品类(奔驰汽车)class BenzCar extends Car{public function run(){echo "{$this->brand} {$this->type} is running..." . PHP_EOL;}}// 定义具体产品类(宝马汽车)class BmwCar extends Car{public function run(){echo "{$this->brand} {$this->type} is running..." . PHP_EOL;}}// 定义具体产品类(苹果手机)class ApplePhone extends Phone{public function call(){echo "{$this->brand} {$this->model} is calling..." . PHP_EOL;}}// 定义具体产品类(华为手机)class HuaweiPhone extends Phone{public function call(){echo "{$this->brand} {$this->model} is calling..." . PHP_EOL;}}<?php// 定义抽象工厂类abstract class AbstractFactory{abstract public function createCar($type);abstract public function createPhone($model);}<?php// 定义具体工厂类(德国工厂)class GermanFactory extends AbstractFactory{public function createCar($type){switch ($type) {case 'Benz':return new BenzCar('Benz', 'C200L');case 'Bmw':return new BmwCar('Bmw', 'X3');default:throw new Exception('Undefined car type.');}}public function createPhone($model){switch ($model) {case 'iPhone':return new ApplePhone('Apple', 'iPhone 11');case 'Huawei':return new HuaweiPhone('Huawei', 'Mate 30');default:throw new Exception('Undefined phone model.');}}}// 定义具体工厂类(中国工厂)class ChineseFactory extends AbstractFactory{public function createCar($type){switch ($type) {case 'Benz':return new BenzCar('奔驰', 'C200L');case 'Bmw':return new BmwCar('宝马', 'X3');default:throw new Exception('Undefined car type.');}}public function createPhone($model){switch ($model) {case 'iPhone':return new ApplePhone('苹果', 'iPhone 11');case 'Huawei':return new HuaweiPhone('华为', 'Mate 30');default:throw new Exception('Undefined phone model.');}}}<?php// 使用德国工厂$germanFactory = new GermanFactory();$car1 = $germanFactory->createCar('Benz');$car1->run(); // output: Benz C200L is running...$phone1 = $germanFactory->createPhone('iPhone');$phone1->call(); // output: Apple iPhone 11 is calling...// 使用中国工厂$chineseFactory = new ChineseFactory();$car2 = $chineseFactory->createCar('Bmw');$car2->run(); // output: 宝马 X3 is running...$phone2 = $chineseFactory->createPhone('Huawei');$phone2->call(); // output: 华为 Mate 30 is calling...抽象工厂模式是一种非常常见的创建型模式,它可以帮助我们封装变化,实现松耦合,同时遵循单一职责原则。在实际开发中,我们可以根据具体的需求,选择不同的抽象工厂模式来实现一系列相关对象的创建。
到此这篇关于PHP抽象工厂模式Abstract Factory Pattern优点与实现方式的文章就介绍到这了,更多相关PHP抽象工厂模式内容请搜索一聚教程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持一聚教程网!