Let’s begin by implementing the Dependency Inversion Principle: our class should depend on an abstraction (i.e. interface).
An interface does not define any method bodies, but it forces any class implementing the interface to define them. If we make our class depend on an interface, then the dependency’s method body can change without breaking our class.
In our example, if we use an ISpeaker
interface, we can make changes to the LoudSpeaker
class as long as it still implements the interface. If it does, we don’t have to touch the Trainer
class to handle the changes.
Instructions
We’ve provided the LoudSpeaker
and QuietSpeaker
classes and the ISpeaker
interface. Both classes implement the interface.
In Trainer.cs, make the speaker
field of type ISpeaker
.
In the constructor in Trainer.cs, instead of instantiating a LoudSpeaker
object, instantiate a QuietSpeaker
object. It also has a Speak()
method, which sets the argument to lower case and surrounds it with ellipses (...
).
The Trainer
behavior may change (as expected) but we didn’t have to change much of the Trainer
code because it relies on the interface ISpeaker
, not the specific LoudSpeaker
or QuietSpeaker
class.