'Pattern'에 해당되는 글 1건

Class A, Class B가 있다고 가정하자.


Class A 내부에서

B bObj = new B(); => A와 B사이에 강한 Dependency가 존재한다.


객체지향에서는 Loose coupling 을 사랑한다.(그래야해...)


-----------------------------------------------------------


그럼 어떻게 deep strong coupling을 지양할 수 있을까??



1. Dependency Injection Pattern

 

2. Service Locator Pattern


위 두개의 Pattern은 두 클래스 간, Loose coupling 을 갖도록 도와준다.

두 Pattern을 정리하기에 앞서, 핵심은 Interface 이다. 이를 기억하자.

핵심은. Interface!!


이유는 Class A, Class B : Interface 가 있다고 할 때,


Class A 내부에서

InterfaceB ib = (Interface)obj;

ib.XXXX();


위와 같이, A입장에서 B 객체를 모르고, Interface를 통해 특정기능만 쓴다면,

이는 A와 B는 loose coupling이다. 


왜냐하면 넘어오면 Interface는 B타입 뿐만 아니라, 그 외에 있을 C, D , E class인지

A는 모르기 때문이다.


하나의 Class에서 다른 Class의 객체를 사용하려 할때, Interface 형태로

사용한다면, Loose coupling을 이루고 있다고 할 수 있다.


-----------------------------------------------


1. Dependency Injection

단어 뜻과 같이, Dependency를 주입하겠다는 것이다.

주입하는 방법은? 크게 두가지가 있겠다.


 1.1 Constructor. 

    Class A의 public A() 생성자에 전달인자로 Interface type의

    객체를 전달받는 형식. 

    

    private Interface gg;

    

    public A(Interface i)

    {

      this.gg = i;

    }


 1.2 또는 Public type의 Property에다가 외부에서 interface를 set 하는 방법.

    A a = new A();

    B b = new B();

    a.gg = (Interface)b;

    

2. ServiceLocator

 Class A는 B를 전혀 모르고, ServiceLocator 객체에 접근해서,

 

 Interface b =  ServiceLocator.GetInstance<Interface>();

 

 위와 같이 사용.

 

 역시나 핵심은 interface를 통해 B class의 기능을 사용하는 것이고,

 여러개의 서비스를 Interface 형태로 전달해줄 수 있는

 매개체를 사용하는 방법.

블로그 이미지

kuku_dass

,