liskov替换原理和界面分离原理之间的区别

问题描述 投票:2回答:2

Liskov替代原理(LSP)和接口隔离原理(ISP)之间是否有核心区别?最终,两者都保证设计具有通用功能的接口,并在您有特殊用途的功能时引入新的接口。

interface solid-principles liskov-substitution-principle interface-segregation-principle
2个回答
4
投票

LSP:接收者必须履行其承诺的合同。

ISP:呼叫者不应依赖过多的接收者。

它们适合的位置:如果应用ISP,则仅使用接收器完整接口的一部分。但是根据LSP,接收者仍然必须遵守该切片。

如果您无法应用ISP,则可能会有违反LSP的诱惑。因为“此方法无关紧要,所以实际上不会调用它。”


0
投票

LSP(Liskov换人):问题:您的孩子中有一个覆盖的未使用/空方法,换句话说,您的孩子扩展了行为,并且不需要它:例如:

/// LSP与ISP

class Animal {
    func fly() {
        // TODO: flying logic
    }

    func eat() {
        // TODO: eating logic
    }
}

class Cat: Animal {
    override func fly() {
        //Hi I'm a cat I cant fly,
        ///here is the Breaking of LSP, I have a different behavior
    }
}

ISP(接口隔离):您已经有一个担负许多职责的接口,并且实现者不需要所有这些东西,因此您需要破坏这些方法并将它们重新组合为关系行为

//this is bad, why, cause it have two different responsibilities
protocol Animal {
    func fly()
    func eat()
}
//to it write
protocol Flyable {
    func fly()
}
protocol Feedable {
    func eat()
}
© www.soinside.com 2019 - 2024. All rights reserved.