Nil*_*aha 13 liskov-substitution-principle interface solid-principles interface-segregation-principle
Liskov 替换原则 (LSP) 和接口隔离原则 (ISP) 之间有什么核心区别吗?最终,两者都保证设计具有通用功能的界面,并在您具有特殊功能时引入新界面。
Jon*_*eid 19
LSP:接收方必须履行其承诺的合同。
ISP:调用者不应该依赖比它需要的更多的接收者接口。
它们适合的地方:如果您使用 ISP,您只会使用接收器完整接口的一部分。但根据 LSP,接收方仍必须遵守该切片。
如果你没有申请 ISP,就会有违反 LSP 的诱惑。因为“这个方法没有关系,它实际上不会被调用”。
它们都是 SOLID 原则
Device类并且它具有callBaba()获取您父亲电话号码然后呼叫他的功能,那么您必须确保该类的callBaba()所有子类中的方法Device执行相同的工作。如果 的任何子类 Device内部有其他行为,callBaba()则意味着您破坏了 LSP违反 Liskov 原则的代码示例。
class Device {
func callBaba() {
print("I will find your father and I will call him")
}
}
class Calculator: Device {
override func callBaba() {
print("Sorry, I don't have this functionality ")
}
}
Run Code Online (Sandbox Code Playgroud)
解决方案
interface CanCall {
func callBaba()
}
class Device {
// all basic shared functions here.
}
class Calculator: Device {
// all functions that calculator can do + Device
}
class SmartPhone: Device implements CanCall {
// all smartphone stuff
func callBaba() {
print("I will find your father and I will call him")
}
}
Run Code Online (Sandbox Code Playgroud)
这违反了 ISP 原则,因为它有两个不同的职责
protocol Animal {
func fly()
func eat()
}
Run Code Online (Sandbox Code Playgroud)
解决方案
protocol Flyable {
func fly()
}
protocol Feedable {
func eat()
}
Run Code Online (Sandbox Code Playgroud)