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
|
<?php
abstract class ParamHandler{
protected $source ;
protected $param = array ();
function __construct( $source ) {
$this ->source = $source ;
}
function addParam( $key , $val ) {
$this ->params[ '$key' ] = $val ;
}
function getAllParams() {
return $this ->params;
}
static function getInstance( $filename ){ //用来获取子类实例,文件类型多时,只 //需在这里加上if语句,然后对应写上子类
if (preg_match( "/\.xml$/i" , $filename )) {
return new XmlParamHandle( $filename );
}
return new TextParamHandler( $filename );
}
abstract function write(); //保证子类实现这两个方法
abstract function read();
}
?>
|
然后下面是子类
1
2
3
4
5
6
7
8
9
10
11
12
|
class XmlParamHandle extends ParamHdndle{
function write(){}
function read(){}
}
class TextParamHandle extends ParamHdndle{
function write(){}
function read(){}
}
|
这样实例化的时候可以这样子
$test = ParamHandler::getInstance("./params.xml");
这样根据传入的params.xml文件会找到对应的类实例化。
本文转自 陈小龙哈 51CTO博客,原文链接:http://blog.51cto.com/chenxiaolong/1702235