PHP工厂模式
<?php
//抽象一个Pserson接口
interface Person
{
//接口中的方法必须是public的
public function showInfo();
}
//创建一个student类,实现接口Person
class Student implements Person
{
//构造方法
public $name;
public $age;
public function __construct($name,$age)
{
$this->name = $name;
$this->age = $age;
}
//实现接口中的方法
public function showInfo()
{
echo '姓名是:'.$this->name.',年龄是:'.$this->age.',现在访问的是学生类中的方法!';
}
}
//创建一个教师类,实现Person接口
class Teacher implements Person
{
//构造方法
public $name;
public $job;
public function __construct($name,$job)
{
$this->name = $name;
$this->job = $job;
}
public function showInfo()
{
echo '姓名是:'.$this->name .',职位是:'.$this->job.',访问的是teacher类中的方法!';
}
}
//使用工厂模式生成实例
class PersonFactory
{
public static function creat($person_type,...$arguements)
{
$class_name = ucfirst($person_type);
if(class_exists($class_name)){
return new $class_name(...$arguements);
}else{
throw new Exception($class_name,1);
}
}
}
$stu1 = PersonFactory::creat('student','玲的','18');
echo $stu1->showInfo();
echo '<br>';
$stu2 = PersonFactory::creat('student','回的','25');
echo $stu2->showInfo();
echo '<br>';
$teacher1 = PersonFactory::creat('teacher','赵老师','语文老师');
echo $teacher1->showInfo();
echo '<br>';
$teacher2 = PersonFactory::creat('teacher','张老师','体育老师');
echo $teacher2->showInfo();
输出
姓名是:玲的,年龄是:18,现在访问的是学生类中的方法! 姓名是:回的,年龄是:25,现在访问的是学生类中的方法! 姓名是:赵老师,职位是:语文老师,访问的是teacher类中的方法! 姓名是:张老师,职位是:体育老师,访问的是teacher类中的方法!

浙公网安备 33010602011771号