code

위임, 구성 및 집계 구분 (Java OO 디자인)

codestyles 2020. 12. 29. 07:07
반응형

위임, 구성 및 집계 구분 (Java OO 디자인)


나는 위임, 구성 및 집계를 서로 구별하고 서로를 사용하는 것이 가장 좋은 경우를 식별하는 데 지속적인 문제에 직면하고 있습니다.

Java OO Analysis and Design 책을 참조했지만 여전히 혼란이 남아 있습니다. 주요 설명은 다음과 같습니다.

위임 : 내 개체가 다른 개체의 기능을 변경하지 않고 그대로 사용하는 경우.

구성 : 내 개체는 내 개체가 파괴 된 후에는 존재할 수없는 다른 개체로 구성되어 있습니다.

Aggregation : 내 객체는 내 객체가 파괴 된 후에도 살 수있는 다른 객체로 구성됩니다.

각 사례와 그 이유를 설명하는 몇 가지 간단한 예를 사용할 수 있습니까? 단순히 다른 객체에 대한 참조를 갖는 내 객체 외에 이러한 예제를 어떻게 설명 할 수 있습니까?


개체는 세 가지 경우 모두에서 다른 개체를 참조합니다. 차이점은 참조 된 개체의 동작 및 / 또는 수명주기에 있습니다. 몇 가지 예 :

  1. 구성 : 집에는 하나 이상의 방이 있습니다. House가 없으면 Room이 존재하지 않으므로 Room의 수명은 House에 의해 제어됩니다.

  2. 집합체 : 블록으로 지어진 장난감 집. 분해 할 수 있지만 블록은 남아 있습니다.

  3. 대표단 : 당신의 상사가 그에게 커피를 가져다달라고 요청했고, 대신 인턴이 대신 해주었습니다. 위임은 연결 유형이 아닙니다 (구성 / 집계와 같은). 후자의 두 가지는 Stack Overflow에서 여러 번 논의되었습니다.

주석에서 각 경우에 구현이 어떻게 다른지 묻고 모든 경우에 관련 객체에 대해 메서드를 호출한다는 것을 관찰합니다. 각각의 경우에 다음과 같은 코드가 있다는 것은 사실입니다.

myRoom.doWork();

myBlock.doWork();

myMinion.doWork();

그러나 차이점은 관련 개체의 수명주기와 카디널리티에 있습니다.

컴포넌트의 경우 House가 생성 될 때 Room이 존재합니다. 그래서 우리는 그것들을 House의 생성자에서 만들 수 있습니다.

Association의 경우 (I 'll use Tire and Car) Cars는 생성자에 타이어를 추가 할 수 있지만 나중에 타이어를 제거하고 변경할 수 있습니다. 따라서 다음과 같은 방법도 있습니다.

 removeTyre(FrontLeft)
 addNewTyre(aTyre, BackRight)

그리고 aTyre 객체가 Factory에서 왔을 가능성이 큽니다. 우리는 newCar의 어떤 메소드에서도 그런 것이 아닙니다 .

Delegation의 경우 델리게이트를 보유 할 멤버 변수가 없을 수도 있습니다.

 resourcingPool().getIntern().getCoffee(SkinnyLatte, workstation 7);

개체 간의 관계는 인턴이 커피를 가져 오는 동안에 만 지속됩니다. 그런 다음 리소스 풀로 돌아갑니다.


대표단

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

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

때의 클라이언트 A호출 methodA, 클래스 A 대표 에 대한 호출 B의 ' methodB.

이론적 해석. 클래스 A는 다른 곳에 속하는 행동을 노출합니다. 이는 클래스 A가 한 클래스에서 상속되지만 해당 클라이언트에는 다른 클래스에서 구현 된 동작이 필요한 단일 상속 언어에서 발생할 수 있습니다. 추가 연구 .

하이브리드 위임

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

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

단순 전달을 포함하는 위임과 상속을 대신하는 위임의 차이점은 수신자가 다음과 같이 예시 된 호출자의 매개 변수를 수락해야한다는 것입니다.

    b.methodB( this );

이론적 해석. 클래스 B인스턴스가 클래스 A에서 B상속 된 경우 와 마찬가지로 클래스 에서 사용할 수있는 기능을 사용할 수 있도록 허용합니다 A. 추가 연구 .

구성

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

  public A() {
  }
}

클래스의 특정 인스턴스에 대한 참조가 더 이상 A존재 하지 않으면 해당 클래스의 인스턴스 B가 삭제됩니다.

이론적 해석. 클래스가 모듈 방식으로 동작과 속성을 정의 할 수 있습니다. 추가 연구 .

집합

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 );
  }
}

class의 특정 인스턴스에 대한 참조가 더 이상 없으면 A해당 클래스 의 인스턴스 B가 삭제되지 않습니다. 이 예에서 A둘 다 C가비지 수집되어야합니다 B.

Rationale. Allows instances to reuse objects. Further study.

Demonstration Without References

The names given to these simple patterns are defined by their referential relationships.


Your book explains quite good so let me elaborate and provide you some examples.

delegation: When my object uses another object's functionality as is without changing it.

Sometime a class may logically need to be big. But big class is not a good coding pratice. Also sometime, some functionalities of a class may be implementable in more than one way and you may want to change that some time.


class FeatureHolder {
 void feature() {
  // Big implementation of the feature that you dont want to put in the class Big
 }
}

class Big {
 private FeatureHolder FH = new FeatureHolder();

 void feature() {
  // Delegate to FeatureHolder.
  FH.feature();
 }

 //.. Other features
}

From the above example, Big.feature() call feature of FH as is without changing it. This way, the class Big does not need to contain the implementation of the feature (separation of labour). Also, feature() can implement differently by other class like "NewFeatureHolder" and Big may choose to use the new feature holder instead.

composition: My object consists of other objects which in turn cannot exist after my object is destryed-garbage collected.

aggregation: My object consists of other objects which can live even after my object is destroyed.

Technially, Composition is "part of" and Aggregation is "refer to" relationship. Your arms are part of you. If you no longer live, your arm will die too. Your cloth is not part of you but you have them; as you can guest, your cloth does not go with you.

In programming, some objects are part of another object and they have no logical meaning without it. For example, a button is composed into a window frame. If a frame is closed, the button has no reason to be around anymore (Composition). A button may have reference to a database (like to refreash data); when the button is eliminated, the database may still be around (Aggregation).

Sorry for my English, Hope this helps


1) Delegation: Man-driver-car example. A Man bought a car. But that man does not know to drive the car. So he will appoint a driver who knows driving a car. So the Man class wants to perform a transportation using car. But it does not have the interacting- functionality/compatibility with car. So he uses a class which has compatibility with car that is driver which is compatible with man class. Assuming that driver can understand what man says

2) Composition: Car simulation is a routine example. To make a car move, wheel rotates. Car class using wheel class rotate functinality as part of its move function, where as wheel is part of car.

3) Aggregation: Car and its colour. Car class object ferrari will have a colour class object red. But colour class object red can be there as individual class, when user search happens with a specification of red colour.

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

반응형