Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

코딩로그

[SOLID] DIP_의존 역전 원칙 본문

YJ/관련 이론

[SOLID] DIP_의존 역전 원칙

Team DAON 2022. 9. 25. 01:33

[DIP]

  • 용어 정리
    • 고수준 모듈 → 변경이 없는 추상화된 모듈
    • 저수준 모듈 → 변하기 쉬운 구체적인 모듈
  • 구체적인 것에 의존하지 말고 추상적인 것에 의존해야 한다
    • 고수준 모듈은 저수준 모듈의 구현에 의존해서는 안 된다
    • 저수준 모듈은 고수준 모듈에서 정의한 추상 타입에 의존해야 한다
  • 자기보다 변화가 쉬운 것에 의존하지 마라
    • 변하기 어려운 것 → interface, abstract
    • 구체적인 class가 아닌 interface에 의존
  • 의존성이 역전되는 시점 → Runtime 시점
  • OCP와 밀접한 관련이 있으며 DIP가 위배되면 OCP도 위배될 가능성이 높다

[Example]

  • Bad Example
// DIP Bad Example

// 특정 Care(Wash)에 의존, 추가 Care를 위해서는 또 다른 class 생성 
class DoWash {
    void doCare(){
        System.out.println("Wash");
    }
}

class DoEat {
    void doCare(){
        System.out.println("Eat");
    }
}

class DoWalk {
    void doCare(){
        System.out.println("walk");
    }
}

class DogCare extends DoWash {
    
}

public class MyClass {
    public static void main(String args[]) {
        DogCare dubuCare = new DogCare();
        
        dubuCare.doCare();
    }
}

 

  • Good Example
// DIP Good Example

// 추상화된 interface(DogCare)에 의존
interface DogCare{
    String doCare();
}

class DoWash implements DogCare{
    
    @Override
    public String doCare(){
        return "Wash";
    }
}

class DoEat implements DogCare{
    
    @Override
    public String doCare(){
        return "Eat";
    }
}

class DoWalk implements DogCare{
    
    @Override
    public String doCare(){
        return "Walk";
    }
}

class DogCareService{
    DogCare dogCare;
    
    public void setDogCare(DogCare dogCare) {
        this.dogCare = dogCare;
    }
    
    public void nowCareService(){
        System.out.println("now service : " + dogCare.doCare());
    }
}

public class MyClass {
    public static void main(String args[]) {
        DogCareService dubuCare = new DogCareService();
        
        dubuCare.setDogCare(new DoEat());
        
        dubuCare.nowCareService();
    }
}

'YJ > 관련 이론' 카테고리의 다른 글

[SOLID] ISP_인터페이스 분리 원칙  (0) 2022.09.25
[SOLID] LSP_리스코프 치환 원칙  (0) 2022.09.25
[SOLID] OCP_개방 폐쇄 원칙  (0) 2022.09.24
[SOLID] SRP_단일 책임 원칙  (0) 2022.09.24