PHP工厂模式

在面向对象编程中, 最通常的方法是一个new操作符产生一个对象实例,new操作符就是用来构造对象实例的。但是在一些情况下, new操作符直接生成对象会带来一些问题。举例来说, 许多类型对象的创造需要一系列的步骤:

  • 你可能需要计算或取得对象的初始设置
  • 选择生成哪个子对象实例

或在生成你需要的对象之前必须先生成一些辅助功能的对象。 在这些情况, 新对象的建立就是一个 “过程”,不仅是一个操作,像一部大机器中的一个齿轮传动。

工厂模式就是解决这个问题而来,工厂模式是我们最常用的实例化对象模式,是用工厂方法代替new操作的一种模式。

根据抽象程度的不同,PHP工厂模式分为三种:

  • 简单工厂模式
  • 工厂方法模式
  • 抽象工厂模式

Example code

<?php
// 琼台博客 www.qttc.net

class Automobile
{
  private $vehicleMake;
  private $vehicleModel;

  public function __construct($make, $model)
  {
    $this->vehicleMake = $make;
    $this->vehicleModel = $model;
  }

  public function getMakeAndModel()
  {
    return $this->vehicleMake . ' ' . $this->vehicleModel;
  }
}

class AutomobileFactory
{
  public static function create($make, $model)
  {
    return new Automobile($make, $model);
  }
}

// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');

print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
分享

TITLE: PHP工厂模式

LINK: https://www.qttc.net/38-php-factory-pattern.html

NOTE: 原创内容,转载请注明出自琼台博客