一、编写 Hello 的 POJO,一个 Hello 接口,两个类实现这个接口的 sayHello() 方法。其中,中文版 CnHello 类,显示中文问候;英文 EnHello 类,显示英文问候。
自己看代码吧,很简单:
版权声明:本博客文章如非特别注明,均为原创,作者保留所有权利!欢迎转载,转载请注明作者
左洸和出处
http://www.blogjava.net/myqiao
Hello.php
<?php

/**
* @author 左洸,http://www.blogjava.net/myqiao
*/
interface Hello {
public function sayHello();
}

//中文版
class EnHello implements Hello{
private $msg;

function getMsg(){
return $this->msg;
}

function setMsg($value){
$this->msg=$value;
}
function sayHello(){
echo "English Version:" . $this->msg;
}
}

//英文版
class CnHello implements Hello{
private $msg;

function getMsg(){
return $this->msg;
}

function setMsg($value){
$this->msg=$value;
}

function sayHello(){
echo "中文版" . $this->msg;
}
}
?>
二、自己设计了一个配置文件,使用 JSON 格式,里面有注释,看看就明白了
//作者:左洸
//http://www.blogjava.net/myqiao

//备注使用双反斜杆
[
//英文版配置

{
//类ID,方便工厂查找
"id": "enHello",

//类名
"class_name":"EnHello",

//类文件
"class_file":"Hello.php",

//属性设置
"properties":[

{
"name":"msg",
"value":"Hello World!"
}
]
},

//中文版配置

{
"id": "cnHello",
"class_name":"CnHello",
"class_file":"Hello.php",
"properties":[

{
"name":"msg",
"value":"世界你好!"
}
]
}
]

三、测试。为类工厂指定上述配置文件。我们可以看见,对配置文件里的不同ID,返回了不同的类实例。调用每个实例的方法,分别输出了中文问候和英文问候。
可见,我们只需要改变配置文件的内容,就可以返回不同的类实例,而不需修改程序源代码。这就实现了简单的 IOC 或者 DI。
test.php
<?php
include_once("ClassFactory.php");
$factory = new ClassFactory("config.json");

$hello=$factory->getBean("enHello");
echo $hello->sayHello() .'<br>';

$hello=$factory->getBean("cnHello");
echo $hello->sayHello();
?>

输出:
English Version:Hello World!
中文版世界你好!
四、
类工厂闪亮登场。实现了一些简单功能,能够解析指定的配置文件,并根据配置文件生成类,同时设置指定的属性值,注释很详细,我就不多解释了。代码如下:
ClassFactory.php
<?php

/**
* Description of ClassFactory
*
* @author 左洸 http://www.blogjava.net/myqiao
*/

class ClassFactory {
private $arr_conf;

function ClassFactory($config_file){
//读取配置文件内容
$handle = fopen($config_file, r);
$content = fread($handle, filesize($config_file));
fclose($handle);

//去除注释
$content=preg_replace("<\/\/.*?\s>","",$content);

//转成数组
$this->arr_conf=json_decode($content,true);
}

function getBean($class_id){
//查找匹配 $class_id 的类
while(true){
//挨个测试
$conf=each($this->arr_conf);

//找不到,返回 null
if($conf==false) return null;

if(strcmp($class_id,$conf["value"]["id"])===0){

//如果匹配则装入类文件
include_once($conf["value"]["class_file"]);

//生成类的实例
//print_r($conf["value"]["class_name"]);
$obj=new $conf["value"]["class_name"]();

//查找被设置的属性
$arr_prop=$conf["value"]["properties"];
while($prop=each($arr_prop)){
//生成属性的设置方法 setXXX ,第一个字母大写
$set_method="set". ucwords($prop["value"]["name"]);

//调用设置方法,并设置预设值
$obj->$set_method($prop["value"]["value"]);
}

//找到第一个,返回实例
return $obj;
}
}
}
}
?>

最后说一下,PHP是动态语言,利用一些语言特性,实现起来很简单,也没用到反射之类的概念。要是用 Java 实现可能要复杂点。
过两天有时间再试一下PHP 版 AOP 面向切面。
版权声明:本博客文章如非特别注明,均为原创,作者保留所有权利!欢迎转载,转载请注明作者
左洸和出处
http://www.blogjava.net/myqiao
posted on 2009-05-01 01:25
左洸 阅读(6094)
评论(23) 编辑 收藏 所属分类:
PHP