1,工厂模式,就是根据参数的不同,返回不同类的实例,工厂模式是创建设计模式的一种。
2,例子
Interface People{
public function get();
}
class Man implements People{
private $name;
function __construct($name){
$this->name=$name;
}
public function get(){
return $this->name;
}
}
class Woman implements People{
private $name;
function __construct($name){
$this->name=$name;
}
public function get(){
return $this->name;
}
}
//简单工厂
class Simplefactory{
public static function build($className,$args){
$className=ucfirst($className);
$reflection=new ReflectionClass($className);//反射类,用来创建类实例
return $reflection->newInstance($args);
}
}
$obj=Simplefactory::build('man','张三');
var_dump($obj);//object(Man)#2 (1) { ["name"]=> string(6) "张三" }
var_dump($obj->get());//string(6) "张三"