您的位置:首页 > 编程语言 > PHP开发

依赖倒转的三种写法[PHP]

2017-08-29 10:10 253 查看
依赖倒转
依赖的三种写法:

构造函数传递依赖对象
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 设计模式