IOC控制反转和DI依赖注入

创建被调用者的工作不再由调用者来完成,因此称为控制反转;

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();

参考资料:https://segmentfault.com/a/1190000002411255

你可能感兴趣的:(IOC控制反转和DI依赖注入)