依赖倒转
依赖的三种写法:@H_301_3@
构造函数传递依赖对象
interface IDriver { public function drive(); } interface ICar { public function run(); } class Driver implements IDriver { protected $car; public function drive(){ $this->car->run(); } public function __construct(ICar $Icar){ $this->car = $Icar; } } class BMW implements ICar { public function run(){ echo 'this is BWM running'; } } class Client{ public function __construct(){ $san = new Driver(new BMW()); $san->drive(); } } $a = new Client();
Setter方法传递对象
interface IDriver { public function drive(); } interface ICar { public function run(); } class driver implements IDriver { protected $car; public function drive(){ $this->car->run(); } public function setter(ICar $ICar){ $this->car = $ICar; } } class BMW implements ICar { public function run(){ echo 'i have a bmw'; } } class Client{ public function __construct(){ $san = new driver(); $san->setter(new BMW()); $san->drive(); } } $a = new Client();
接口声明依赖对象
<?PHP /** * User: didi * Date: 2017/8/29 * Time: 上午7:31 */ interface IDriver { public function drive(Icar $car); } interface ICar { public function run(); } class Driver implements IDriver { public function drive(Icar $car){ $car->run(); } } class BMW implements ICar{ public function run(){ echo 'BMW RUN'; } } class Client{ public function __construct(){ $san = new Driver(); $bmw = new BMW(); $san->drive($bmw); } } $a = new Client();原文链接:https://www.f2er.com/javaschema/282770.html