scnjl0 2017-04-29
php工厂模式就如其名字一样,不用实例化类,工厂类为你自动生成了对象。(程序员的对象再也不用new了,工厂自动生成了,还想要什么样的就生成什么样的,突然就走上人生巅峰了!)可以分为简单工厂模式,方法工厂模式和抽象工厂模式
也可以叫静态工厂方法模式,其核心就是用一个静态方法,在静态方法中实例化对象。如下图:
//工厂接口定于厂房方法
interface Factory{
function workshop();
}
//领导类实现厂房方法->要很多钱
class Leader implements Factory{
function workshop(){
echo '要很多钱<br/>';
}
}
//员工类实现厂房方法->要很多砖头
class Staff implements Factory{
function workshop(){
echo '要很多砖头';
}
}
//工厂模式获取工厂
class getFactory{
//静态方法,实例化领导和员工类
static function getLeader(){
return new Leader;
}
static function getStaff(){
return new Staff;
}
}
$leader = getFactory::getLeader();
$staff = getFactory::getStaff();
$leader->workshop();
$staff->workshop();
?>
代码部分:
interface Factory{
function workshop();
}
class Leader implements Factory{
function workshop(){echo '要钱<br/>';}
}
class Staff implements Factory{
function workshop(){echo '要砖';}
}
interface getPeople{
function createPeople();
}
class getLeader implements getPeople{
function createPeople(){
return new Leader;
}
}
class getStaff implements getPeople{
function createPeople(){
return new Staff;
}
}
class getFactory{
function createFactory(){
$getLeader=new getLeader();
$leader=$getLeader->createPeople();
$leadersay=$leader->workshop();
$getLeader=new getStaff();
$staff=$getLeader->createPeople();
$staffsay=$staff->workshop();
}
}
$getFactory=new getFactory;
$getFactory->createFactory();
<?php. if (!empty($_POST)) {. $data1 = $_POST["data1"];$data2 = $_POST["data2"];$fuhao = $_POST["fuh