看了一下国外网友的说法。如下:
An example of Composition is where you have an instance of a class within another class, instead of inheriting from it
"Composition is when I create an object of Class A
inside Class B
(instead of subclassing Class B
from Class A
).
用一个例子来区分继承和组合
Animal:
Skin animalSkin
Organs animalOrgans
Mammal:
private Animal _animalRef
Hair/fur mammalFur
warm-blooded-based_cirulation_system heartAndStuff
Person:
private Mammal _mammalRef
string firstName
string lastName
The advantage to this approach is that the types Mammal
and Person
do not have to conform to the interface of their previous parent. This could be a good thing because sometimes a change to the superclass can have serious effects on the subclasses. They still can have access to the properties and behaviours of these classes through their private instances of these classes, and if they want to expose these former-superclass behaviours, they can simply wrap them in a public method.