工厂模式解决的是如何不通过 new 关键字建立实例对象的方法。
工厂模式是一种类,它具有为你创建对象的某些方法,你可以使用工厂类创建对象而不使用 new 关键字。这样,如果你想要更改所创建的对象类型只需要修改工厂类即可,使用该工厂类的所有代码会自动更改。
工厂模式往往配合接口一起使用,这样应用程序就不必要知道这些被实例化的类的具体细节,只要知道工厂类返回的是支持某个接口的类就可以方便的使用了。
简单代码实现如下:
<?php
/**
* 工厂模式示例
*/
/**
* 定义一个人类抽象类接口
*/
interface Person
{
public function showInfo();
}
/**
* 实现人类抽象类接口的教师类
*/
class Teacher implements Person
{
public function showInfo()
{
echo "I'm a teacher." . PHP_EOL;
}
}
/**
* 实现人类抽象类接口的学生类
*/
class Student implements Person
{
public function showInfo()
{
echo "I'm a student." . PHP_EOL;
}
}
/**
* 人类工厂
*/
class PersonFactory
{
public static function factory($personType) {
// 将传入的类名首字母大写
$className = ucfirst($personType);
// 如果传入的类存在,则实例化该类,否则抛异常
if ( class_exists( $className) ) {
return new $className;
} else {
throw new Exception("Class: " . $className . " not exists !");
}
}
}
$teacher = PersonFactory::factory("teacher");
$teacher->showInfo(); // 输出:I'm a teacher.
$student = PersonFactory::factory("student");
$student->showInfo(); // 输出:I'm a student.
$other = PersonFactory::factory("other");
$other->showInfo(); // 因为不存在 Other 类,因此会抛出:Fatal error: Uncaught Exception: Class: Other not exists ! 异常