PHP 工厂模式浅析


//抽象出一个人的接口
interface Person{
public function showInfo();
}
//继承于人的学生类
class Student implements Person{
public function showInfo()
{
// TODO: Implement showInfo() method.
echo "我是一个学生";
}
}
//继承于人的教师类
class Teacher implements Person{
public function showInfo()
{
// TODO: Implement showInfo() method.
echo "我是一个老师";
}
}
//人类工厂
class PersonFactory{
public static function factory($person_type){
    //传进来的人的类型,首字母大写
$class_name = ucfirst($person_type);
if (class_exists($class_name)){
return new $class_name;
}else{
throw new Exception("类:".$class_name."不存在");
}
}
}
//学生类的实例化
$student = PersonFactory::factory('student');
$student->showInfo();
posted @ 2018-04-27 17:47  申息  阅读(114)  评论(0编辑  收藏  举报