bumdream / morning_study

1 stars 0 forks source link

2일차 SOLID - OCP #2

Open bumdream opened 6 years ago

hongsukchoi commented 6 years ago

B. OCP (개방폐쇄의 원칙: Open Close Principle)

확장에는 열려있고, 변경에는 닫혀있어야 한다는 원리 = 변경 가능한 부분에 대해 추상화를 잘해야한다.

적용법

1. 변경(확장)될 것과 변하지 않을 것을 엄격히 구분합니다. 변경될 것 -> 인터페이스 변하지 않을 것 -> 클래스

2. 이 두 모듈이 만나는 지점에 인터페이스를 정의합니다. 잘모르겠다. 두 모듈이 상이한 클래스(예: 기타, 피아노)를 뜻해서 공통된 부분을 인터페이스로 한다는건지 인터페이스와 클래스가 분리되는 지점에서 인터페이스를 정의한다는 건지

3. 구현에 의존하기보다 정의한 인터페이스에 의존하도록 코드를 작성 합니다. 모호한 구문 같은데, 재사용성을 높이도록 인터페이스에 반복되는 코드를 넣으란 얘기같다.

bumdream commented 6 years ago

개방폐쇄원칙(OCP - open closed principle)

image

SubtitleParser parser =ParserFactory.Create(SAMI);
parser.parse(file);

OCP 적용 사례

적용전


public class Rectangle{ 
    public double length;
    public double width;
}

public class Circle{ 
    public double radius; 
}

public class AreaCalculator{ 
    public double calculateRectangleArea(Rectangle rectangle){    
          return rectangle.length *rectangle.width;  
   }
    public double calculateCircleArea(Circle circle){
    return (22/7)*circle.radius*circle.radius;
     } 
}

적용후

public interface Shape{
  public double calculateArea();
}

public class Rectangle implements Shape{
  double length;
  double width;
  public double calculateArea(){
    return length * width;
  }
}

public class Circle implements Shape{
  public double radius;
  public double calculateArea(){
    return (22/7)*radius*radius;
  }
}