CS/언어

[JAVA] Delegation & Composition & Aggregation

pythaac 2022. 6. 24. 23:45

https://stackoverflow.com/questions/1384426/distinguishing-between-delegation-composition-and-aggregation-java-oo-design

 

Distinguishing between delegation, composition and aggregation (Java OO Design)

I am facing a continuing problem distinguishing delegation, composition and aggregation from each other, and identifying the cases where it's the best to use one over the other. I have consulted a...

stackoverflow.com

 

정의

  • 객체가 다른 객체를 참조하는 3가지 방법
  • 참조되는 객체의 behaviour / lifecycle로 분류됨

 

Delegation

  • clinet가 class A methodA()를 호출할 때, class A class B methodB() 호출을 위임
  • 참조되는 객체의 behaviour와 관련
  • 발생할 수 있는 환경
    - 단일 상속 언어(Single-inheritance Language)
    - class A가 이미 상속을 받음
    - 다른 class의 behaviour가 필요
public class A {
  private B b = new B();

  public void methodA() {
    b.methodB();
  }
}

 

Composition

  • class A의 인스턴스에 대한 참조가 사라지면, class B는 destroy
  • 참조되는 객체의 lifecycle과 관련
  • class가 "modular fashion"처럼 behaviour와 attribute를 결정 가능
public class A {
  private B b = new B();

  public A() {
  }
}

 

Aggregation

  • class A의 인스턴스에 대한 참조가 사라져도, class B가 destroy되지 않음
  • 참조되는 객체의 lifecycle과 관련
  • 아래 예시에서 B가 destroy되기 전에 A와 C가 garbage collect 되어야 함
public class A {
  private B b;

  public A( B b ) {
    this.b = b;
  }
}

public class C {
  private B b = new B();

  public C() {
    A a = new A( this.b );
  }
}