<?php //工厂模式 class Automobile { private $vehicleMake; private $vehicleModle; public function __construct($make,$model) { $this->vehicleMake = $make; $this->vehicleModle = $model; } public function getMakeAndModel() { return $this->vehicleMake.' '.$this->vehicleModle; } } class AutomobileFactory { public static function create($make,$model) { return new Automobile($make,$model); } } $veyron = AutomobileFactory::create('Bugatti','Veyron'); print_r($veyron->getMakeAndModel()); ?>
上面的代码用来一个工厂来创建 Automobile 对象。用这种方式创建对象有两个好处: 首先,如果你后续需要更改,重命名或替换 Automobile 类,你只需要更改工厂类中的代码,而不是在每一个用到 Automobile 类的地方修改; 其次,如果创建对象的过程很复杂,你也只需要在工厂类中写,而不是在每个创建实例的地方重复地写。
上一篇:
php设计模式之单例模式简单事例
下一篇:
shell脚本下执行sql语句