简单说明IoC
<?php //Ioc ———— 设计方式 //控制反转 Inversion of Control //依赖关系的转移 //依赖抽象而非实践 //用于解决高层应用依赖 底层组件,软件移植性差(修改困难)的问题 //实例: /* class soft{ private $writer; public function __construct(){ $this->writer = new FloppyWriter; } public function save(){ $this->writer->SaveToFloppy(); } } //造成高层对底层的依赖__使程序无法重用 不好的设计 class FloppyWriter{ public function saveToFloppy(){ echo __METHOD__; } } $soft = new soft; $soft->save() */ ##########################改进########################## //定义一个接口约定 interface IDeviceWriter { public function saveToDevice(); } class soft{ private $_writer; public function setWriter($name){ $this->_writer = $name; } public function save(){ $this->_writer->saveToDevice(); } } //软盘储存 class FoppyWriter implements IDeviceWriter{ public function saveToDevice(){ echo __METHOD__; } } //USB储存 class USBWriter implements IDeviceWriter{ public function saveToDevice(){ echo __METHOD__; } } //将高层依赖 转移到 "依赖注入" $soft= new soft(); $writer= new USBWriter; $soft->setWriter($writer); $soft->save();
时间: 2024-11-08 03:43:49