Class composition and inheritance
Composition gives an object a collaborator, while inheritance gives a class the behavior and type relationship of a parent class.
How it works
Separate the checkout’s job from the discount rule. Checkout decides when to ask for a discount and which purchase data to supply. A rule computes the discount. Swapping the object holding the rule changes one decision without creating a new kind of checkout.
Walk through an example
A checkout can hold a DiscountPolicy and call it for a price. Different discount policies can plug in without changing checkout code.
What to watch for
Use inheritance only when the subtype can satisfy the parent type’s expectations. Prefer composition when you simply want to reuse a capability.
Check your understanding
How can it use either rule without being a discount rule itself?
See the example and explanation
- Worked example
- Given
Checkout needs to switch between two discount rules. - Answer
Give Checkout a DiscountPolicy field.
The checkout delegates discount calculation to its collaborator rather than inheriting one specific rule.