What is the difference between association, aggregation and composition?

后端 未结 19 1853
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 01:44

What is the difference between association, aggregation, and composition? Please explain in terms of implementation.

19条回答
  •  名媛妹妹
    2020-11-22 02:03

    For two objects, Foo and Bar the relationships can be defined

    Association - I have a relationship with an object. Foo uses Bar

    public class Foo { 
        void Baz(Bar bar) {
        } 
    };
    

    Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

    public class Foo {
        private Bar bar = new Bar(); 
    }
    

    Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

    public class Foo { 
        private Bar bar; 
        Foo(Bar bar) { 
           this.bar = bar; 
        }
    }
    

提交回复
热议问题