HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
🗨️
IOC & DI & Others
🗨️

IOC & DI & Others

notion image
IOC의 목적을 달성하기 위한 패턴 중 DI를 제외한 다른 방식들을 정리해보자.

Template Method Pattern

Intent

  • 알고리즘의 뼈대를 추상 클래스의 Final Method로 정의 - 템플릿 메소드
  • 구체적인 실행 로직은 템플릿을 상속/ 구현 하여 Subclass에서 구현

Intent ~ IOC

  • Template Method의 입장에서 자신이 실행되는 시점, 협력에 대한 의존관계의 연결 - Template이 관리
  • Template의 입장에서 자신은 로직의 ‘실행’ 만을 책임짐
  • 로직의 구현(Template Method), 로직의 생성 모두 외부 (Subclass) 로 부터 전달 받음
template method pattern uml
template method pattern uml

c.f) Strategy Pattern 은 Template Method Pattern처럼 변하지 않는 부분과 변하는 부분 (구체 로직) 을 분리하는 목적으로 사용되지만 Strategy Pattern은 상속이 아닌 위임으로 목적을 달성함
Strategy Pattern - DI를 활용한 IOC에 자주 활용되는 패턴
Intent
  • 알고리즘 제품군을 정의하고 각각을 캡슐화하여 상호 교환 가능하도록 만들자
  • 클라이언트와 독립적으로 알고리즘을 변경할 수 있도록 하자
strategy pattern uml
strategy pattern uml
  • Context가 Strategy를 외부로 부터 주입받는 IOC의 예시가 된다.
  • Context가 구체 전략이 아닌 Strategy에만 의존하기 때문에 가능한 이야기
 
Strategy Pattern & Dependency Injection
Strategy Pattern & Dependency Injection

Template Callback Pattern

프로그래밍에서 콜백 또는 콜애프터 함수는 다른 코드의 인수로서 넘겨주는 실행 가능한 코드를 말한다.
프로그래밍에서 콜백 또는 콜애프터 함수는 다른 코드의 인수로서 넘겨주는 실행 가능한 코드를 말한다.
  • Template Method Pattern의 Template 적인 특성
  • Strategy Pattern 중 callback
이 강조된 패턴이다.
 
Template Callback Pattern
Template Callback Pattern
Template (Context)는 callback을 필드로 가질 필요 없이 실행 로직의 인자로만 전달 받는다.

Factory Method Pattern

Intent

  • 객체 생성에대한 Interface 정의. Subclass가 구체 타입을 정해서 Instantiate 하게 하기
notion image
interface Product { } abstract class Factory { protected abstract Product factoryMethod(); } class ConcreteProduct implements Product { } class ConcreteFactory extends Factory { protected Product factoryMethod() { return new ConcreteProduct(); } } public class Client { public static void main(String[] args) { Factory creator = new ConcreteFactory(); Product product = creator.factoryMethod(); System.out.println(product.getClass().getSimpleName()); } }

Intent ~ IOC

Factory로 선언된 creator 변수는 factoryMethod를 실행하는 시점에 자신이 어떤 Product를 생성할 지 알 수 없다.
위 코드에서는 선언당시 할당받은 ConcreteFactory의 로직이 동작 하지만 중간에 다른 로직으로 대체 되었을 수도 있다.
즉 Factory의 입장에서 실행시점에 자신이 어떤 Product를 생성할 지는 전혀 알 수 없다. Client가 자신에게 할당한 로직을 수행하는 것만을 책임질 뿐이다.

Service Locator Pattern

 
public class MemberService { private final JsonParser jsonParser; public MemberService() { this.jsonParser = ServiceLocator.jsonParser(); } public String parseString(Member member) { return this.jsonParser.parseString(member); } }
public class ServiceLocator { public static JsonParser jsonParser() { //경우에 따라 Singleton이나 다른 Scope로 구현을 하기도 한다. return new JacksonParser(); } }

Intent

서비스를 구현한 구체 클래스는 숨긴 채로 어디에서나 서비스에 접근할 수 있게 한다.
 
안티패턴이다.
  • see) 서비스 로케이터는 안티패턴이다.