리μ€μ½ν μΉν μμΉ(Liskov Substitution Principle)
μμ ν΄λμ€λ μ΅μν μμ μ λΆλͺ¨ ν΄λμ€μμ κ°λ₯ν νμλ μνν μ μμ΄μΌ νλ€.
Example
μλλ λμ΄μ λλΉλ₯Ό κ°μ§λ Rectangle
ν΄λμ€ μ
λλ€.
class Rectangle {
private int width;
private int height;
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return this.height;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return this.width;
}
public int area() {
return this.width * this.height;
}
}
Rectangle
μ μμλ°κ³ μλ Square
λΌλ ν΄λμ€μ
λλ€. setHight(int value)
μ setWidth(int value)
λ₯Ό Overrideνκ³ μμ΅λλ€.
class Square extends Rectangle {
@Override
public void setHeight(int value) {
this.width = value;
this.height = value;
}
@Override
public void setWidth(int value) {
this.width = value;
this.height = value;
}
}
ν μ€νΈ μ½λλ₯Ό λ³ΌκΉμ?
λμ΄ 4, λλΉ 5λ‘ μ€μ νμ¬ λμ΄λ₯Ό ꡬνκ³ νμΈνλ ν¨μμ
λλ€. λΆλͺ¨ ν΄λμ€μΈ Rectangle
μ κ²°κ³Ό κ°μ trueλ₯Ό νμΈ ν μ μμ§λ§ Square
λ falseλ‘ νμΈ ν μ μμ΅λλ€.
class Test {
static boolean checkAreaSize(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
if(r.area() != 20 ){ // Error Size
return false;
}
return true;
}
public static void main(String[] args){
Test.checkAreaSize(new Rectangle()); // true
Test.checkAreaSize(new Square()); // false
}
}
μμ μμλ LSP
λ₯Ό μλ°ν νλμ μμ λ‘ λ³Ό μ μμ΅λλ€. μμ ν΄λμ€ Square
λ λΆλͺ¨ ν΄λμ€ Rectangle
μ area()
κΈ°λ₯μ μ λλ‘ νμ§ λͺ»νκ³ μμ΅λλ€.
κ·Έλ¬λ©΄ κ³Όμ° Square
λ Rectangle
μ μμμ΄ λ§μκΉλΌλ μμ¬μ ν΄λ΄μΌ ν©λλ€. μμ ν΄λμ€λ μ΅μν μμ μ λΆλͺ¨ ν΄λμ€μμ κ°λ₯ν νμλ μνν μ μμ΄μΌ νκΈ° λλ¬Έμ
λλ€.
ν΄κ²° λ°©λ²
- μμμ κ΄κ³λ₯Ό μ κ±°νλ λ°©λ².
- κΈ°λ₯μ μ λλ‘ νμ§ λͺ»νλ
area()
λ₯Ό μμ ν΄λμ€λ‘ μ΄λμν€λ λ°©λ².
Result
- LSPλ₯Ό ν΅ν΄ μμ ν΄λμ€κ° λΆλͺ¨ ν΄λμ€μ μν μ μΆ©μ€ν νλ©΄μ νμ₯ν΄λκ°μΌ νλ€λ κ²μ μκ² λμλ€.