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

前端之家收集整理的这篇文章主要介绍了依赖倒转的三种写法[PHP]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
依赖倒转

依赖的三种写法:

构造函数传递依赖对象
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

猜你在找的设计模式相关文章