Code _php techniques for implementing factory design patterns using interfaces in PHP

Source: Internet
Author: User

Interface in PHP can only play a role in the definition of constraint classes, although not as intuitive as C#/java, but based on OOP encapsulation requirements, the use of interfaces can improve the scalability of the program, such as the implementation of proxy design mode.

Copy Code code as follows:

<?php
Human interface
Interface Ihuman
{
function GetName ();
}
Male human, realize human interface
Class Manclass implements Ihuman
{
Get Name method
Public Function GetName ()
{
Return "I ' m man." <br> ";
}
}
Woman human, realize human interface
Class Womanclass implements Ihuman
{
Get Name method
Public Function GetName ()
{
Return "I ' m Woman." <br> ";
}
}
class factory, produce different instance objects as needed to return
Class Manfactory
{
Get instance object from parameters
Public Function Getihuman ($IHuman = "mans")
{
if ($IHuman = = "Woman")
{
return new Womanclass ();
}
else if ($IHuman = = "Man")
{
return new Manclass ();
}
Else
{
return null;
}
}
Get woman class directly
Public Function Getwoman ()
{
return new Womanclass ();
return new Manclass ();
}
Get the man type 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.