简体   繁体   English

在课堂上或作为成员实施接口

[英]Implement interface in class or as member

什么时候直接在类中实现接口有用,什么时候让接口类型的字段成员更好?

It's a question of whether you want your class to be able to do something , or have something . 这是一个问题,您是否希望自己的班级能够做某事拥有某事

case 1 impl: 情况1暗示:

public class Car : ICanPlayRadio
{
    // impl. ICanPlayRadio
    public void TurnOnRadio() { ... }
}

case 2 impl: 情况2暗示:

public class Car
{
    public IRadio Radio { get; set;}
}

use case 1: 用例1:

Car myCar = new Car();
myCar.TurnOnRadio(); // my car can turn on the radio

use case 2: 用例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. 在此示例中,情况2对我而言更有意义。 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). 对Radio属性使用接口的好处是car类可以接受IRadio实例(通常传递给构造函数)。 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. 因此,您可以创建两辆具有两种不同无线电实现方式的汽车,但是当涉及到打开无线电时,您可以确保它们都能按照接口的b / c方式完成工作。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM