您的位置:首页 > 编程语言 > PHP开发

PHP设计模式---工厂模式

2012-07-02 11:51 543 查看
工厂模式的作用在与,可以根据输入参数或者应用程序配置的不同类创建一种专门用来实例化并返回其他类的实例的类。工厂模式包含一个名为factory()的方法,这个方法必须返回一个对象

interface IImage{
function getHeight();
function getWidth();
function getData();
}
//png图片
class Image_PNG implements IImage{
private $_width,$_height,$_data;
public function __construct($file){
$this->_file=$file;
$this->_parse();
}
private function _parse(){
//
echo 'You are a png img!';
}
function getHeight(){
return $this->_height;
}
function getWidth(){
return $this->_width;
}
function getData(){
return $this->_data;
}
}
//jpeg
class Image_JPEG implements IImage{
private $_width,$_height,$_data,$_file;
public function __construct($file){
$this->_file=$file;
$this->_parse();
}
private function _parse(){
//*************
$img=Image::getImageInfo($this->_file);
$this->_width=$img[0];
echo 'You are a jpeg image o!';
}
function getHeight(){
return $this->_height;
}
function getWidth(){
return $this->_width;
}
function getData(){
return $this->_data;
}
}
//图片格式工厂
class ImageFactory{
public static function factory($file){
$pathParts=pathinfo($file);
switch (strtolower($pathParts['extension'])){
case 'jpg':
$ret=new Image_JPEG($file);
break;
case 'png':
$ret=new Image_PNG($file);
break;
default:// 有问题
}
if ($ret instanceof  IImage){
return $ret;
}else {
//有问题
}
}
}
//调用
$image=ImageFactory::factory("D:\\My Documents\\My Pictures\\aa.jpg");
echo $image->getWidth();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: