What is the difference between Composition and Association relationship?

前端 未结 8 1985
眼角桃花
眼角桃花 2020-12-01 04:05

In OOP, what is the difference between composition (denoted by filled diamond in UML) and association (denoted by empty diamond in UML) relationship between classes. I\'m a

8条回答
  •  猫巷女王i
    2020-12-01 04:17

    Owning and using.

    Composition: the object with the reference owns the object referred to, and is responsible for its "lifetime", its destruction (and often creation, though it may be passed in). Also known as a has-a relationship.

    Association: the object with the reference uses the object referred to, may not be an exclusive user, and isn't responsible for he referred-to object's lifetime. Also known as a uses-a relationship.

    The OP comments:

    Can you provide a real world example. Also, what is aggregation? – Marc

    Aggregation: an Association that is from whole to part, and that can't be cyclic.

    Examples:

    Composition: a Car has-an Engine, a Person has-an Address. Basically, must have, controls lifetime.

    Association: A Car has-a Driver, some class instance has-an ErrorLogger. Lifetime not controlled, may be shared.

    Aggregation: A DOM (Document Object Model, that is the objects that make up a tree of HTML elements) Node has-a (an array of) child Nodes. The Node is top (well, higher) level; it "contains" its children, they don't contain it.

提交回复
热议问题