PHP设计模式之:工厂模式
2013-12-20 14:07
513 查看
工厂模式:
由工厂类根据参数来决定创建出哪一种产品类的实例;工厂类是指包含了一个专门用来创建其他对象的方法的类。所谓按需分配,传入参数进行选择,返回具体的类。工厂模式的最主要作用就是对象创建的封装、简化创建对象操作。
简单的说,就是调用工厂类的一个方法(传入参数)来得到需要的类;
代码实现:
示例1(最基本的工厂类):
//使用工厂类解析图像文件 interface IImage { function getWidth(); function getHeight(); function getData(); } class Image_PNG implements IImage { protected $_width,$_height,$_data; public function __construct($file){ $this->_file = $file; $this->_parse(); } private function _parse(){ //完成PNG格式的解析工作 //并填充$_width,$_height和$_data $this->_data = getimagesize($this->_file); list($this->_width,$this->_height)=$this->_data; } public function getWidth(){ return $this->_width; } public function getHeight(){ return $this->_height; } public function getData(){ return $this->_data; } } class Image_JPEG implements IImage { protected $_width,$_height,$_data; public function __construct($file){ $this->_file = $file; $this->_parse(); } private function _parse(){ //完成JPEG格式的解析工作 //并填充$_width,$_height和$_data //$this->_width = imagesx($this->_file); //$this->_height = imagesy($this->_file); $this->_data = getimagesize($this->_file); list($this->_width,$this->_height)=$this->_data; } public function getWidth(){ return $this->_width; } public function getHeight(){ return $this->_height; } public function getData(){ return $this->_data; } } //工厂类 class ImageFactory { public static function factory($file){ $filename = pathinfo($file); switch(strtolower($filename['extension'])){ case 'jpg': $return = new Image_JPEG($file); break; case 'png': $return = new Image_PNG($file); break; default: echo '图片类型不正确'; break; } if($return instanceof IImage){ return $return; }else{ echo '出错了'; exit(); } } } $image = ImageFactory::factory('images/11.jpg'); var_dump($image->getWidth()); echo '<br>'; print_r($image->getheight()); echo '<br>'; print_r($image->getData());
View Code
相关文章推荐
- php常用设计模式(策略模式/单例模式/工厂模式)
- 魔兽争霸之PHP设计模式-工厂模式[Factory]
- PHP设计模式之 单例模式 工厂模式 实例讲解
- php设计模式-工厂模式
- php设计模式之工厂模式(工厂模式实现计算器功能)
- php设计模式(工厂模式)
- 设计模式php实例:工厂模式
- PHP设计模式笔记:使用PHP实现工厂模式
- PHP 设计模式 单例模式 工厂模式 注册模式
- php设计模式 — 工厂方法模式(多态性工厂模式) (虚拟构造子模式)
- PHP设计模式 -- 工厂模式
- php设计模式(1)-工厂模式
- php模式设计之 工厂模式
- 浅谈php设计模式(1)---工厂模式
- PHP面向对象深入理解之四(设计模式-工厂模式)
- PHP设计模式---工厂模式
- php部分---面向对象,设计模式(单例模式、工厂模式)、oop六大原则;
- php设计模式-工厂模式
- php 设计模式(注册器模式+工厂模式+数据库映射模式,单例模式+工厂模式+注册器模式混合使用)
- php设计模式 工厂模式