PHP设计模式工厂模式

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

 1 interface IImage{
 2  function getHeight();
 3  function getWidth();
 4  function getData();
 5 }
 6 //png图片
 7 class Image_PNG implements IImage{
 8  private $_width,$_height,$_data;
 9  public function __construct($file){
10   $this->_file=$file;
11   $this->_parse();
12  }
13  private function _parse(){
14   //
15   echo 'You are a png img!';
16  }
17  function getHeight(){
18    return $this->_height;  
19  }
20  function getWidth(){
21   return $this->_width; 
22  }
23  function getData(){
24   return $this->_data;
25  }
26 }
27 //jpeg 
28 class Image_JPEG implements IImage{
29  private $_width,$_height,$_data,$_file;
30  public function __construct($file){
31   $this->_file=$file;
32   $this->_parse();
33  }
34  private function _parse(){
35   //*************
36   $img=Image::getImageInfo($this->_file);
37   $this->_width=$img[0];
38   echo 'You are a jpeg image o!';
39  }
40  function getHeight(){
41    return $this->_height;  
42  }
43  function getWidth(){
44   return $this->_width; 
45  }
46  function getData(){
47   return $this->_data;
48  }
49 }
50 //图片格式工厂
51 class ImageFactory{
52  public static function factory($file){
53   $pathParts=pathinfo($file);
54   switch (strtolower($pathParts['extension'])){
55    case 'jpg':
56     $ret=new Image_JPEG($file);
57     break;
58    case 'png':
59     $ret=new Image_PNG($file);
60     break;
61     default:// 有问题
62   }
63   if ($ret instanceof  IImage){
64    return $ret;
65   }else {
66    //有问题
67   }
68  }
69 }
70 //调用
71 $image=ImageFactory::factory("D:\\My Documents\\My Pictures\\aa.jpg");
72  echo $image->getWidth();

 

原文地址:https://www.cnblogs.com/zzming/p/2572959.html