PHP工厂模式的三种形式的示例代码详解
<?php // 简单工厂模式 interface ICar { function run(); } class BMWCar implements ICar { public function run() { echo 'bmw run!<br/>'; } } class AuDiCar implements ICar { public function run() { echo 'audi run!<br/>'; } } /** * 简单工厂 */ class FactorySimple { /* public static function createBmw() { return new BMWCar(); } public static function createAudi() { return new AuDiCar(); } */ public static function createCar($type) { switch($type) { case 'bmw': return new BMWCar(); case 'audi': return new AuDiCar(); default: throw new Exception('type error!'); } } } // ------------------------------------------------------ // ------------------------------------------------------ // 工厂方法模式 interface CreateCar { //工厂类接口 function create(); } /** * bmw car factoyr */ class BmwFactory implements CreateCar { public function create() { return new BMWCar(); } } /** * audi car factory */ class AuDiFactory implements CreateCar { public function create() { return new AuDiCar(); } } // ------------------------------------------------------ // ------------------------------------------------------ // 抽象工厂模式 class WhiteBMWCar implements ICar { public function run() { echo 'white bmwcar run!<br/>'; } } class BlackBMWCar implements ICar { public function run() { echo 'black bmwcar run!<br/>'; } } class WhiteAuDiCar implements ICar { public function run() { echo 'white audicar run!<br/>'; } } class BlackAuDiCar implements ICar { public function run() { echo 'black audicar run!<br/>'; } } // 提供一系列的接口 interface ICarCreate { function createBmw(); function createAuDi(); } /** * create white car */ class WhiteCarFactory implements ICarCreate { // white bmw public function createBmw() { return new WhiteBMWCar(); } // white audi public function createAuDi() { return new WhiteAuDiCar(); } } /** * create black car */ class BlackCarFactory implements ICarCreate { // black bmw public function createBmw() { return new BlackBMWCar(); } // black audi public function createAuDi() { return new BlackAuDiCar(); } }
相关文章:
以上是PHP工厂模式的三种形式的示例代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!