Reputation: 51
When is it usefull to implement the interface directly in a class and when is it better to have a field member of the interface type?
Upvotes: 1
Views: 81
Reputation: 2317
It's a question of whether you want your class to be able to do something, or have something.
case 1 impl:
public class Car : ICanPlayRadio
{
// impl. ICanPlayRadio
public void TurnOnRadio() { ... }
}
case 2 impl:
public class Car
{
public IRadio Radio { get; set;}
}
use case 1:
Car myCar = new Car();
myCar.TurnOnRadio(); // my car can turn on the radio
use case 2:
Car myCar = new Car();
myCar.Radio.TurnOn(); // my car has a radio, it can be turned on
In this example, case 2 makes more sense to me. It all depends on your model.
UPDATE:
"Whats the benefit in using an interface for the radio?"
The benefit of using an interface for the Radio property is that the car class can accept IRadio instances (usually passed into constructor). So you can create two cars having two different radio implementations, but when it comes to turning the radio on, you can be sure they both can do it b/c of the interface working as a contract of what can be done.
public class FMRadio : IRadio { ... }
public class AppleCarPlay : IRadio { ... }
Car volvo740 = new Car(new FMRadio());
Car audiA7 = new Car(new AppleCarPlay());
volvo740.Radio.TurnOn(); // turns on last FM radio frequency
audiA7.Radio.TurnOn(); // plays my favorite spotify playlist
Upvotes: 2