코샵
끄적끄적 코딩 공방
코샵

인기 글

  • 분류 전체보기 (478) N
    • MongoDB (4)
    • 일기장 (4)
    • Unity (138)
      • Tip (41)
      • Project (1)
      • Design Pattern (8)
      • Firebase (6)
      • Asset (2)
    • 파이썬 (127)
      • Basic (40)
      • OpenCV (8)
      • Pandas (15)
      • PyQT (3)
      • SBC(Single Board Computer) (1)
      • 크롤링 (14)
      • Fast API (29)
      • Package (6)
    • Linux (4)
    • C# (97)
      • Algorithm (11)
      • Window (7)
    • TypeScript (47) N
      • CSS (9) N
    • Git (11)
    • SQL (5)
    • Flutter (10)
      • Tip (1)
    • System (1)
    • BaekJoon (6)
    • Portfolio (2)
    • MacOS (1)
    • 유틸리티 (1)
    • 서비스 (6)
    • 자동화 (3)
    • Hobby (10)
      • 물생활 (10)
      • 식집사 (0)
전체 방문자
오늘
어제

최근 댓글

최근 글

반응형
hELLO · Designed By 정상우.
코샵

끄적끄적 코딩 공방

C#

객체지향의 5대 원칙 SOLID : Open-Closed Principle

2023. 4. 28. 11:46
반응형

Open-Closed Principle

Open-Closed Principle은 개방-폐쇄 원칙으로, 기존 코드를 변경하지 않으면서 기능을 추가할 수 있도록 설계해야 한다는 원칙입니다. 이것은 클래스의 수정보다는 확장을 통해 시스템을 변경해야 한다는 것을 의미합니다.

Open-Closed Principle의 예

다음은 Open-Closed Principle의 예시입니다.

public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }
}

public class AreaCalculator
{
    public double CalculateArea(Rectangle[] shapes)
    {
        double area = 0;
        foreach (var shape in shapes)
        {
            area += shape.Width * shape.Height;
        }
        return area;
    }
}

public class Circle
{
    public double Radius { get; set; }
}

public class AreaCalculator2
{
    public double CalculateArea(object[] shapes)
    {
        double area = 0;
        foreach (var shape in shapes)
        {
            if (shape is Rectangle)
            {
                Rectangle r = (Rectangle)shape;
                area += r.Width * r.Height;
            }
            else if (shape is Circle)
            {
                Circle c = (Circle)shape;
                area += c.Radius * c.Radius * Math.PI;
            }
        }
        return area;
    }
}

위의 예제는 사각형과 원의 넓이를 계산하는 AreaCalculator 클래스를 Open-Closed Principle을 지키지 않은 예시입니다. 이것은 새로운 도형이 추가될 때마다 AreaCalculator 클래스를 수정해야 한다는 것을 의미합니다.

반면, Open-Closed Principle을 지킨 예시는 객체들이 동일한 인터페이스를 구현하도록하는 것입니다. 이렇게 하면 기존 코드를 수정하지 않고도 새로운 클래스를 추가할 수 있습니다.

public interface IShape
{
    double Area();
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

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

public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Radius * Radius * Math.PI;
    }
}

public class AreaCalculator3
{
    public double CalculateArea(IShape[] shapes)
    {
        double area = 0;
        foreach (var shape in shapes)
        {
            area += shape.Area();
        }
        return area;
    }
}

이렇게 하면 AreaCalculator3 클래스에서 IShape 인터페이스를 구현하는 모든 클래스를 사용할 수 있습니다. 새로운 클래스를 추가하기 위해서는 해당 인터페이스를 구현하기만 하면 되므로 기존 코드를 수정할 필요가 없습니다.

Open-Closed Principle의 장점

Open-Closed Principle을 지키면 코드의 확장성이 높아지기 때문에 새로운 기능을 추가하거나 기존 기능을 변경할 때 기존 코드를 수정할 필요가 없습니다. 이것은 코드의 재사용성을 높이고 유지보수성을 개선하는 데 도움이 됩니다.

결론

Open-Closed Principle은 기존 코드를 변경하지 않으면서 기능을 추가할 수 있도록 설계해야 한다는 객체지향의 5대 원칙 중 하나입니다. 이것은 클래스의 수정보다는 확장을 통해 시스템을 변경해야 한다는 것을 의미합니다. 이번 글을 통해 Open-Closed Principle에 대해 더욱 자세히 알아보았습니다.

저작자표시 비영리 변경금지 (새창열림)

'C#' 카테고리의 다른 글

객체지향의 5대 원칙 SOLID : Interface Segregation Principle  (0) 2023.04.30
객체지향의 5대 원칙 SOLID : Liskov Substitution Principle  (0) 2023.04.29
객체지향의 5대 원칙 SOLID : Single Responsibility Principle  (0) 2023.04.27
C# : System.String  (0) 2023.04.26
C# : Refactoring  (0) 2023.04.20
    'C#' 카테고리의 다른 글
    • 객체지향의 5대 원칙 SOLID : Interface Segregation Principle
    • 객체지향의 5대 원칙 SOLID : Liskov Substitution Principle
    • 객체지향의 5대 원칙 SOLID : Single Responsibility Principle
    • C# : System.String
    코샵
    코샵
    나의 코딩 일기장

    티스토리툴바