控制反转与以来注入

控制反转

简单的一段代码如下:

<?php

class Person {
    public function eat() {
        $restaurant = new Mcdonald();
        echo "I am eating at ".$restaurant->getName()."\n"; 
    }   
}

class Mcdonald {
    public function getName() {
        return "McDonald";
    }   
}

$person = new Person();
$person->eat();

如果我也会在  Kentucky 吃饭,或者在PizzaHut吃饭,那么我们或许可以写成下面的形式:

<?php

class Person {
    private $restaurant;
    public function __construct ($restaurant) {
        $this->restaurant = $restaurant;
    }

    public function eat() {
        echo "I am eating at ".$this->restaurant->getName()."\n"; 
    }
}

interface Restaurant {
    public function getName();
}

class Mcdonald implements Restaurant {
    public function getName() {
        return "McDonald";
    } 
}

class Kentucky implements Restaurant {
    public function getName() {
        return "Kentucky";
    } 
}


$person = new Person(new Kentucky());
$person->eat();
$person = new Person(new Mcdonald());
$person->eat();
通过构造函数传递restaurant的依赖,这个过程就是依赖注入。


我们添加wear函数。

<?php

class Person {
    private $restaurant;
    private $shoe;
    public function __construct ($restaurant, $shoe) {
        $this->restaurant = $restaurant;
        $this->shoe = $shoe;
    }

    public function eat() {
        echo "I am eating at ".$this->restaurant->getName()."\n"; 
    }
    public function wear() {
        echo "I am wearing ".$this->shoe->getName()."\n"; 
    }
}

interface Restaurant {
    public function getName();
}

class Mcdonald implements Restaurant {
    public function getName() {
        return "McDonald";
    } 
}

class Kentucky implements Restaurant {
    public function getName() {
        return "Kentucky";
    } 
}

interface Shoe {
    public function getName();
}

class Nike implements Shoe {
    public function getName() {
        return "Nike";
    }
}

class Addidas implements Shoe {
    public function getName() {
        return "Addidas";
    }
}

$restaurant = new Kentucky();
$shoe = new Addidas();
$person = new Person($restaurant, $shoe);
$person->eat();
$person->wear();
在使用的过程中,我们一次注入了$restaurant和$shoe。


Kentucky
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值