摘要:<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018-11-19
* Time: 11:10
*/
//工厂模式:根据用户需求,动态生成类的实例
//Test&
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018-11-19
* Time: 11:10
*/
//工厂模式:根据用户需求,动态生成类的实例
//Test 二个类
class Computer
{
public function work()
{
return '学习编程';
}
}
class Auto
{
public function run()
{
return '到处游玩';
}
}
//创建Student类,该类中是直接用到了上面的二个类
// class Student // 这样会导致Student严重依赖 Computer 这个类
// {
// public function study()
// {
// $computer = new Computer();
// return '计算机'.$computer-> work();
// }
// public function drive()
// {
// $auto = new Auto();
// return '汽车'.$auto->run();
// }
// }
// $student = new Student;
// echo $student->study();
// echo '<br />';
// echo $student->drive();
// echo '<br /><hr /><br />';
//解决方法测试
//1.创建工厂类: Factory
class Factory
{
public static function create($className)
{
switch (strtolower($className)) {
case 'computer':
return new Computer();
break;
case 'auto':
return new Auto();
break;
}
}
}
class Student1
{
public function study()
{
$computer = Factory::create('Computer'); //Factory::create(); 知识点 Factory方法
return '计算机'.$computer-> work();
}
public function drive()
{
$auto = Factory::create('Auto');;
return '汽车'.$auto->run();
}
}
$student1 = new Student1;
echo $student1->study();
echo '<br />';
echo $student1->drive();