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

后端 未结 5 2099
遇见更好的自我
遇见更好的自我 2020-12-12 09:08

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 o

5条回答
  •  囚心锁ツ
    2020-12-12 10:03

    In a very simple sentence I can say:

    Delegation is: delegate behaviour to other class when you do not want to change it. by change I mean during run time. for example you delegate driver to car class that driver wont change while driving.

    Composition is: when you want to use behaviour of family of classes (one or more classes, that implements an interface) that you might change during run time. but you should consider these classes can not exist with out main classes, such as rooms of a hotel. If you remove hotel all rooms of hotel will not exist.

    Aggregation is: same as composition but classes can exist without main class.

提交回复
热议问题