[Unity]리스코프 치환 원칙

Hoojung Ahn·2024년 5월 23일

리스코프 치환 원칙(Liskov Substitution Principle, LSP)은 객체 지향 프로그래밍의 SOLID 원칙 중 하나로, 서브 타입은 언제나 자신의 기반 타입(base type)으로 교체할 수 있어야 한다는 개념이다. 즉, 프로그램에서 어떤 객체를 그 객체의 하위 클래스 객체로 교체하더라도 프로그램의 동작은 변하지 않아야 한다.

리스코프 치환 원칙은 상속을 올바르게 사용하는 방법을 제시하며, 객체지향 설계의 견고성을 높이는 데 중요한 역할을 한다.

  • 리스코프 치환 원칙 예시
    원칙을 지키지 않는 경우를 원칙을 지키는 코드로 수정하는 예시

원칙을 지키지 않는 경우

'''csharp

public class Rectangle
{
public virtual int Width { get; set; }
public virtual int Height { get; set; }

public int Area()
{
    return Width * Height;
}
}

public class Square : Rectangle
{
public override int Width
{
    set { base.Width = base.Height = value; }
}

public override int Height
{
    set { base.Width = base.Height = value; }
}
}

public class Program
{
public static void Main()
{
    Rectangle rect = new Rectangle { Width = 4, Height = 5 };
    Console.WriteLine($"Rectangle Area: {rect.Area()}");  // 20

    Rectangle square = new Square { Width = 4, Height = 5 };
    Console.WriteLine($"Square Area: {square.Area()}");  // 25 (예상과 다름)
}
}

'''

Square는 Rectangle의 서브 클래스지만, Width와 Height를 설정하는 방식이 다르다. Square 클래스는 항상 정사각형이 되도록 Width와 Height를 동일하게 설정한다. 따라서 Square 객체를 Rectangle 타입으로 사용하면 예상치 못한 결과가 발생할 수 있다.

원칙을 지키는 경우
리스코프 치환 원칙을 지키기 위해, Rectangle과 Square 간의 상속 관계를 다시 생각해보고, 더 적절한 디자인을 적용.

'''csharp

public abstract class Shape
{
public abstract int Area();
}

public class Rectangle : Shape
{
public int Width { get; set; }
public int Height { get; set; }

public override int Area()
{
    return Width * Height;
}
}

public class Square : Shape
{
public int SideLength { get; set; }

public override int Area()
{
    return SideLength * SideLength;
}
}

public class Program
{
public static void Main()
{
    Shape rect = new Rectangle { Width = 4, Height = 5 };
    Console.WriteLine($"Rectangle Area: {rect.Area()}");  // 20

    Shape square = new Square { SideLength = 4 };
    Console.WriteLine($"Square Area: {square.Area()}");  // 16
}
}

수정 버전에서는 Shape라는 추상 클래스가 있고, Rectangle과 Square가 이를 상속받는다. 각 클래스는 자신의 면적 계산 방식을 구현한다. 이로써 Rectangle과 Square는 상속 관계가 아니지만, 공통된 인터페이스를 통해 다형성을 유지하면서 리스코프 치환 원칙을 지킬 수 있다.

0개의 댓글