依赖注入(DI)和控制反转(IOC)【回顾】

时间:2022-04-28 21:31:46

  在java开发中广泛的使用了IOC的思想,在PHP中同样也在广泛使用。

 interface Coder
{
public function coding();
}

实现类Javaer

 class Javaer implements Coder
{
var $name; public function __construct($name)
{
$this->name = $name;
}
public function coding()
{
echo "$this->name.is coding java code.<br>";
}
}

实现类Phper

 class Phper implements Coder
{
var $name; public function __construct($name)
{
$this->name = $name;
}
public function coding()
{
echo "$this->name.is coding php code.<br>";
}
}

业务逻辑类Task

 class Task
{
var $name;
var $owner; public function __construct($name)
{
$this->name = $name;
} public function setOwner($owner){
$this->owner = $owner;
} public function start()
{
echo "$this->name.started!<br>";
$this->owner->coding();
}
}

测试

         $task = new Task("Task #1");
// $owner = new Phper("xiaohb");
$owner = new Javaer("xiaoxiao");
$task->setOwner($owner);
$task->start();

代码的可维护和拓展性显而易见了

相关文章