Home  >  Article  >  Backend Development  >  Detailed explanation of the three forms of sample code of PHP factory pattern

Detailed explanation of the three forms of sample code of PHP factory pattern

黄舟
黄舟Original
2017-03-18 14:39:013148browse

PHPFactory patternDetailed explanation of the three forms of sample code

';
	}
}

class AuDiCar implements ICar {
	
	public function run() {
		echo 'audi run!
'; } } /** * 简单工厂 */ 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!
'; } } class BlackBMWCar implements ICar { public function run() { echo 'black bmwcar run!
'; } } class WhiteAuDiCar implements ICar { public function run() { echo 'white audicar run!
'; } } class BlackAuDiCar implements ICar { public function run() { echo 'black audicar run!
'; } } // 提供一系列的接口 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn