设计模式七:工厂模式
工厂模式:
分为简单工厂,方法工厂,和抽象工厂。
一:简单工厂
简单工厂的作用是实例化对象,而不需要调用者知道该对象具体对应的子类。
<?php class MysqlLog{ public function log(){ echo '记录Mysql错误'.PHP_EOL; } } class ErrorLog{ public function log(){ echo '记录程序错误'.PHP_EOL; } } /** * 工厂类 */ class Factory{ public function make($abstract){ switch($abstract){ case 'mysql': return new MysqlLog(); case 'error': return new ErrorLog(); } } } /** * 日志调用类 */ class Log{ protected $logs; public function __construct($abstracts) { $factory = new Factory(); foreach($abstracts as $value){ $this->logs[$value] = $factory->make($value); } } public function write($abstract){ return $this->logs[$abstract]->log(); } } $log = new Log(['mysql','error']); $log->write('mysql'); $log->write('error');
二:方法工厂
在简单工厂的基础上进行改进,由一个工厂变为多个工厂。
class MysqlLog{ public function log(){ echo '记录Mysql错误'.PHP_EOL; } } class ErrorLog{ public function log(){ echo '记录程序错误'.PHP_EOL; } } /** * 工厂类 */ class MysqlFactory{ public function make(){ return new MysqlLog(); } } class ErrorFactory{ public function make(){ return new ErrorLog(); } } /** * 日志调用类 */ class Log{ protected $logs; public function __construct() { $this->logs['mysql'] = (new MysqlFactory())->make(); $this->logs['error'] = (new ErrorFactory())->make(); } public function write($abstract){ return $this->logs[$abstract]->log(); } } $log = new Log(); $log->write('mysql'); $log->write('error');
三:抽象工厂
相对于方法工厂,抽象工厂对外提供的是一个抽象接口。抽象工厂,抽象方法。
<?php /** * 功能抽象类 */ interface LogInterface{ public function log(); } class MysqlLog implements LogInterface{ public function log(){ echo '记录Mysql错误'.PHP_EOL; } } class ErrorLog implements LogInterface{ public function log(){ echo '记录程序错误'.PHP_EOL; } } /** * 工厂抽象类 */ interface LogFactoryInterface { public function mysqlMake(); public function errorMake(); } class LogFactory implements LogFactoryInterface{ public function mysqlMake(){ return new MysqlLog(); } public function errorMake(){ return new ErrorLog(); } } /** * 日志调用类 */ class Log{ protected $logs; public function __construct() { $logFactory = new LogFactory(); $this->logs['mysql'] = $logFactory->mysqlMake(); $this->logs['error'] = $logFactory->errorMake(); } public function write($abstract){ return $this->logs[$abstract]->log(); } } $log = new Log(); $log->write('mysql'); $log->write('error');