一个很简单的工厂模式。代码如下:
<?php
interface Person
{
public function sex();
}
class Man implements Person
{
public function sex()
{
echo "I'm a Man".PHP_EOL;
}
}
class Women implements Person
{
public function sex()
{
echo "I'm a Women".PHP_EOL;
}
}
class Factory
{
public static function getObject($name)
{
return new $name();
}
}
$man = Factory::getObject('Man');
$man->sex();
$women = Factory::getObject('Women');
$women->sex();
/**
output results
I'm a Man
I'm a Women
*/
代码很简单,重要的是思想。