Rumah >pembangunan bahagian belakang >tutorial php >PHP工厂模式的三种形式的示例代码详解
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(); } }
相关文章:
Atas ialah kandungan terperinci PHP工厂模式的三种形式的示例代码详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!