创建被调用者的工作不再由调用者来完成,因此称为控制反转;
<?php
interface IDeviceWriter {
public function saveToDevice();
}
class Business {
private $writer;
public function setWriter($writer) {
$this->writer = $writer;
}
public function save() {
$this->writer->saveToDevice();
}
}
class FloppyWriter implements IDeviceWriter {
public function saveToDevice()
{
echo __METHOD__ . PHP_EOL;
}
}
class UsbWriter implements IDeviceWriter {
public function saveToDevice()
{
echo __METHOD__ . PHP_EOL;
}
}
$biz = new Business();
$biz->setWriter(new FloppyWriter());
$biz->save();
$biz->setWriter(new UsbWriter());
$biz->save();