在java开发中广泛的使用了IOC的思想,在PHP中同样也在广泛使用。
1 interface Coder 2 { 3 public function coding(); 4 }
实现类Javaer
1 class Javaer implements Coder 2 { 3 var $name; 4 5 public function __construct($name) 6 { 7 $this->name = $name; 8 } 9 public function coding() 10 { 11 echo "$this->name.is coding java code.<br>"; 12 } 13 }
实现类Phper
1 class Phper implements Coder 2 { 3 var $name; 4 5 public function __construct($name) 6 { 7 $this->name = $name; 8 } 9 public function coding() 10 { 11 echo "$this->name.is coding php code.<br>"; 12 } 13 }
业务逻辑类Task
1 class Task 2 { 3 var $name; 4 var $owner; 5 6 public function __construct($name) 7 { 8 $this->name = $name; 9 } 10 11 public function setOwner($owner){ 12 $this->owner = $owner; 13 } 14 15 public function start() 16 { 17 echo "$this->name.started!<br>"; 18 $this->owner->coding(); 19 } 20 }
测试
1 $task = new Task("Task #1"); 2 // $owner = new Phper("xiaohb"); 3 $owner = new Javaer("xiaoxiao"); 4 $task->setOwner($owner); 5 $task->start();
代码的可维护和拓展性显而易见了
时间: 2024-10-20 12:00:22