When to Use Composition vs Inheritance
When to Use
π¨βπΌ Let's build a notification system. We need to decide whether to use
inheritance or composition for different scenarios.
π¨ Open
and:
- Create a
Loggerclass with alog(message: string)method - Create an
EmailServiceclass that uses composition (has-a Logger) - Create a
FileLoggerclass that uses inheritance (is-a Logger) - Create a
ConsoleLoggerclass that uses inheritance (is-a Logger) - Demonstrate when each approach is appropriate
π° Think about the relationship: Is it "is-a" or "has-a"?