- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 435字
- 2021-06-25 20:52:30
Liskov Substitution Principle
Barbara Liskov states that, Derived types must be completely substitutable for their base types. The Liskov Substitution Principle (LSP) is strongly related to subtyping polymorphism. Based on subtyping polymorphism in an object-oriented language, a derived object can be substituted with its parent type. For example, if we have a Car object, it can be used in the code as a Vehicle.
The LSP states that, when designing the modules and classes, we must make sure that the derived types are substitutable from a behavior point of view. When the derived type is substituted with its supertype, the rest of the code will operate with it as it is the subtype. From this point of view, the derived type should behave as its supertype and should not break its behavior. This is called strong behavioral subtyping.
In order to understand the LSP, let's take an example in which the principle is violated. While we are working on the car-service software, we discover we need to model the following scenario. When a car is left for service, the owner leaves the car. The service assistant takes the key and, when the owner leaves, he goes to check that he has the right key and that he has spotted the right car. He simply goes to unlock and lock the car, then he puts the key in a designated place with a note on it so the mechanic can easily pick it up when he has to inspect the car.
We already have defined a Car class. We are now creating a Key class and adding two methods into the car class: lock and unlock. We add a corresponding method, so the assistant checks the key matches the car:
public class Assistant
{
void checkKey(Car car, Key key)
{
if ( car.lock(key) == false ) System.out.println("Alert! Wrong
key, wrong car or car lock is broken!");
}
}
The diagram is as follows:

While working on our software, we realize that buggies are sometimes repaired through the car service. As buggies are four-wheel cars, we create a Buggy class, which is inherited from the Car:

Buggies don't have doors, so they cannot be locked or unlocked. We implement our code accordingly:
public bool lock(Key key)
{
// this is a buggy so it can not be locked return false;
}
We design our software to work with cars, regardless of whether they are buggies or not, so in the future we might extend it with other types of cars. A problem may arise from the fact that cars are expected to be locked and unlocked.
- Java逍遙游記
- 多媒體CAI課件設計與制作導論(第二版)
- 新一代通用視頻編碼H.266/VVC:原理、標準與實現
- 劍指Offer(專項突破版):數據結構與算法名企面試題精講
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- Visual C++開發入行真功夫
- 區塊鏈技術與應用
- MySQL從入門到精通(軟件開發視頻大講堂)
- Essential C++(中文版)
- 持續集成與持續交付實戰:用Jenkins、Travis CI和CircleCI構建和發布大規模高質量軟件
- 計算機應用基礎項目化教程
- Clojure Polymorphism
- 基于GPU加速的計算機視覺編程:使用OpenCV和CUDA實時處理復雜圖像數據
- After Effects CC技術大全
- Data Manipulation with R(Second Edition)