简单工厂模式(Simple Factory Pattern)又被称为静态工厂方法模式(Static Factory Method Pattern),具体指创建一个类似于工厂的类,通过对该类中成员方法的调用返回不同类型的对象。
<?php
header('content-type:text/html;charset=utf-8');
//人类接口
interface people{
function say();
}
//student类
class student implements people{
public function say(){
echo "我是学生";
}
}
//工人类
class worker implements people{
public function say(){
echo "我是工人";
}
}
//简单工厂类
class factory{
static function createstudent(){
return new student();
}
static function createworker(){
return new worker();
}
}
工厂方法:定义一个用于创建对象的接口,让子类决定哪个类实例化。 他可以解决简单工厂模式中的封闭开放原则问题。
<?php
header('content-type:text/html;charset=utf-8');
//人类接口
interface people{
function say();
}
//student类
class student implements people{
public function say(){
echo "我是学生";
}
}
//工人类
class worker implements people{
public function say(){
echo "我是工人";
}
}
//简单工厂类
class factory{
static function createstudent(){
return new student();
}
static function createworker(){
return new worker();
}
}
interface createPeople{
public function create();
}
class FactoryStudent implements createPeople{
public function create(){
return new student();
}
}
class FactoryWoker implements createPeople{
public function create(){
return new worker();
}
}
class Client{
public function test(){
$factory=new FactoryStudent();
$man=$factory->create();
$man->say();
$factory=new FactoryWoker();
$man=$factory->create();
$man->say();
}
}
$demo = new Client;
$demo->test();
?>