依赖倒置原则(DSP)
<?php// 司机开奔驰,未用依赖倒置原则的写法class Benz{ public function run(){ return " Benz is runing!!!"; }}class Driver{ public function drive(Benz $car){ echo $car -> run(); }}class Client{ public static function doing(){ $driver = new Driver(); $driver -> drive( new Benz() ); }}Client :: doing();// 那么如果司机想开宝马呢?,是不是就要修改Driver了,这就违反了开闭原则了,怎么能只在Client添加代码就让宝马车也会开呢?interface ICar{ //定义一个汽车接口 public function run();}class BMW implements ICar{ public function run(){ return "BMW is runing !!!"; }}class Benz implements ICar{ public function run(){ return "Benz is runing !!!"; }}interface IDriver{ //定义一个司机接口,以防以后有A照,B照,C照的 public function drive(ICar $car);}class Driver implements IDriver{ public function drive(ICar $car){ echo "<br>" . $car -> run(); }}class Client{ public static function doing(){ $driver = new Driver(); $driver -> drive( new BMW() ); //开宝马 $driver -> drive( new Benz() ); //开奔驰 . . . . }}Client :: doing();?>
这么简单,学会了吧?依赖倒置原则核心一句话:面向接口编程。