Home > php教程 > php手册 > php中使用接口实现工厂设计模式的代码

php中使用接口实现工厂设计模式的代码

WBOY
Release: 2016-06-13 12:00:08
Original
1006 people have browsed it

接口在php只能起到约束类的定义作用,虽不像c#/java那么直观,但基于oop的封装要求,使用接口可以提高程序的可扩展性,如实现代理设计模式。

复制代码 代码如下:


//人类接口
interface IHuman
{
function GetName();
}
//男人类,实现人类接口
class ManClass implements IHuman
{
//获取姓名方法
public function GetName()
{
return "I'm man."."
";
}
}
//女人类,实现人类接口
class WomanClass implements IHuman
{
//获取姓名方法
public function GetName()
{
return "I'm Woman."."
";
}
}
//类工厂,根据需要生产不同实例对象返回
class ManFactory
{
//根据参数获取实例对象
public function GetIHuman($IHuman="man")
{
if($IHuman=="woman")
{
return new WomanClass();
}
else if($IHuman=="man")
{
return new ManClass();
}
else
{
return null;
}
}
//直接获取woman类
public function GetWoman()
{
return new WomanClass();
//return new ManClass();
}
//直接获取man类
public function GetMan()
{
return new ManClass();
}
}
$ManFactory=new ManFactory();
$ManClass=$ManFactory->GetIHuman();
echo $ManClass->GetName();
$IHuman=$ManFactory->GetIHuman("woman");
echo $IHuman->GetName();
$Woman=$ManFactory->GetWoman();
echo $Woman->GetName();
$Man=$ManFactory->GetMan();
echo $Man->GetName();
?>


运行结果:
I'm man.
I'm Woman.
I'm Woman.
I'm man.
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template