Friday, August 22, 2008

Composition vs. Aggregation

Composition


  • Composition allows us to use behavior from a family of other classes, and to change that behavior at runtime
  • Composition is most powerful when we want to use behavior defined in an interface, and then choose from a variety of implementations of that interface, at both compile time and run time
  • Composition is like a string "has a" relationship - the components that make up the parent cannot existing without the parent
  • When an object is composed of other objects, and the owning object is destroyed, the objects that are part of the composition goes away too
  • A real world example may be - a human body is composed of different parts hands, legs etc. But without the body, the parts cannot exist alone
  • A code example using a car example
    Car car = new  Car();
    car.setProperty("engine", new Engine());
  • When the "car" object is destroyed, so is the Engine object created in the second line. It is destroyed along with the owning object
  • Simply there is no reference for the component object outside the owning object


  • In composition, the object composed of other behaviors owns those behaviors
  • When the object is destroyed, so are all of its behaviors
  • The behaviors in a composition do not exist outside of the composition
  • The main object owns the composed behavior, so if that object goes away, all the behavior does too
  • The UML diagram for composition uses a darkened diamond - signifying the strong relationship





Aggregation


  • Aggregation is when one class is used as part of another class, but still exists outside of that other class
  • Aggregation is a kind of association that specifies a whole/part relationship between the aggregate(whole) and component part
  • This relationship between the aggregate and component is a weak "has a" relationship as the component may survive the aggregate object
  • Unlike composition, here, the component object may outlive the aggregate object
  • A code example using a Course/Student example
    course.addStudent(student);
  • The student object has its own behavior, and its state can influence the state of the course object (for instance, the aggregate mark for the course etc.)
  • Even if the course object is destroyed, student object will live on

  • The UML diagram for aggregation uses an empty diamond





Aggregation vs. Composition


  • The easiest way to figure out when to use what is to ask - does the object whose behavior I want to use exist outside of the object that uses its behavior?
  • If the object does make sense existing on its own, then we should use aggregation, if not use composition

Saturday, August 16, 2008