PHPFactory patternDetailed explanation of the three forms of sample code
<?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(); } }
Related articles:
A brief analysis of the PHP factory pattern
Simple instructions for using PHP factory mode
Analysis of the benefits of PHP factory mode
The above is the detailed content of Detailed explanation of the three forms of sample code of PHP factory pattern. For more information, please follow other related articles on the PHP Chinese website!