Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

依赖反转、依赖注入 #8

Open
gamebody opened this issue Apr 22, 2019 · 0 comments
Open

依赖反转、依赖注入 #8

gamebody opened this issue Apr 22, 2019 · 0 comments

Comments

@gamebody
Copy link
Owner

如果有这样一个需求,一个人要去旅游,可以用不同的交通工具,比如自行车、小汽车等。
我们可以写出下面的代码。

// 接口,提供开的能力
interface IDriveable {
    driver(): void
}

// 自行车
class Bike implements IDriveable {
    constructor() {

    }
    driver(): void {
        console.log('骑自行车')
    }
}

// 小汽车
class Car implements IDriveable {
    constructor() {
        
    }
    driver(): void {
        console.log('开车')
    }
}

class Person {
    private bike: Bike
    private car: Car

    // 构造函数中创建交通工具相关的实例
    constructor() {
        // this.bike = new Bike()
        this.car = new Car()
    }

    travel() {
        // this.bike.driver()
        this.car.driver()
    }
}

// 创建Person实例,旅游
new Person().travel()

可以看到这种代码的表现方式,虽然直白,但是,我们想更换交通方式的时候,比较麻烦,改动了constructor()中和travel()中的代码

而且源代码依赖上讲,Person依赖的是Bike或Car

其实,想想,不管什么交通工具,只要提供driver的能力(interface IDriveable),我们Person就能开,没必要在意他是什么。

interface IDriveable {
    driver(): void
}

class Person {
    // 能开的工具
    private driveable: IDriveable

    constructor() {
        // 自行车能开
        this.driveable = new Bike()
    }

    travel() {
        this.driveable.driver()
    }
}

new Person().travel()

我们还可以将能开的工具,通过构造函数传进来,我们之前说Person从代码角度讲依赖于 IDriveable 提供的能力,把这种能力的对象通过构造函数传进来,叫 依赖注入

class Person {
    private driveable: IDriveable

    constructor(driveable: IDriveable) {
        this.driveable = driveable
    }

    travel() {
        this.driveable.driver()
    }
}
const bike = new Bike()
new Person(bike).travel()

我们也可以提供接口来实现上面依赖注入的功能

class Person {
    private driveable: IDriveable

    constructor() {
        
    }

    travel() {
        if (this.driveable) {
           this.driveable.driver() 
        }
    }
    
    setDriveable(driveable: IDriveable) {
        this.driveable = driveable
    }
}
const bike = new Bike()
const person = new Person()

person.setDriveable(bike)
person.travel()

这样Person就不依赖Bike或Car了,依赖的是 IDriveable ,而 Bike和Car 依赖 IDriveable

Person -> Bike || Car(Person依赖Bike或Car)

Person -> IDriveable <- Bike || Car (依赖的转变)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant