-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-factory-pattern.php
More file actions
87 lines (74 loc) · 1.75 KB
/
simple-factory-pattern.php
File metadata and controls
87 lines (74 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* Factory-pattern 工厂模式
*
* @abstract 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
* @author xjin
* @version 2015/3/4
*/
interface IImage
{
public function getHeight();
}
// Png 图片处理
class Image_PNG implements IImage
{
private $_width, $_height, $_data;
public function __construct($file)
{
$this->_file = $file;
$this->_parse();
}
private function _parse()
{
// 完成PNG格式的解析工作
// 并填充$_width,$_height,$_data;
}
public function getHeight()
{
return $this->_height;
}
}
// Jpeg 图片处理
class Image_JPEG implements IImage
{
private $_width, $_height, $_data;
public function __construct($file)
{
$this->_file = $file;
$this->_parse();
}
private function _parse()
{
// 完成JPEG格式的解析工作
// 并填充$_width,$_height,$_data;
}
public function getHeight()
{
return $this->_height;
}
}
// 工厂模式的应用
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 {
// 有问题
}
}
}
//当使用图像文件名调用 工厂方法时,根据传入的文件类型不同,取得不同对象。