Home > Backend Development > PHP Tutorial > Code to use interface to implement factory design pattern in php_PHP tutorial

Code to use interface to implement factory design pattern in php_PHP tutorial

WBOY
Release: 2016-07-21 15:18:26
Original
890 people have browsed it

Interfaces in PHP can only play a role in defining constraint classes. Although not as intuitive as C#/Java, based on the encapsulation requirements of OOP, using interfaces can improve the scalability of the program, such as implementing the proxy design pattern.

Copy code The code is as follows:

//Human interface
interface IHuman
{
function GetName();
}
//Male human, implements human interface
class ManClass implements IHuman
{
//Get name method
public function GetName ()
{
return "I'm man."."
";
}
}
//Female human, implements human interface
class WomanClass implements IHuman
{
//Get name method
public function GetName()
{
return "I'm Woman."."
";
}
}
//Class factory, produce different instance objects as needed and return
class ManFactory
{
//Get instance objects according to parameters
public function GetIHuman($IHuman="man")
{
if($IHuman=="woman")
{
return new WomanClass();
}
else if($IHuman=="man")
{
return new ManClass();
}
else
{
return null;
}
}
//Get the woman class directly
public function GetWoman()
{
return new WomanClass();
//return new ManClass();
}
//Get the man class directly
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();
? >

Run result:
I'm man.
I'm Woman.
I'm Woman.
I'm man.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325543.htmlTechArticleInterface in php can only play a role in defining constraint classes. Although it is not as intuitive as c#/java, it is based on oop's encapsulation requirements, the use of interfaces can improve the scalability of the program, such as implementing agent design models...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template