c# - 没有完全理解为什么我会在一个类中有一个接口,而不是从它继承
问题描述
我正在查看 SOLID 原则,并发现了一些 SRP 代码。
我有这段代码,但我不知道为什么我会有一个接口,以我在下面的方式声明?这对我有什么好处?我在这里找到,它显示了一个解决方案,但它并没有真正解释代码如何更好地工作或为什么事情是这样的。
我不明白的是:
IGateUtility _gateUtility;
在public class ServiceStation
, 和它的正下方是带有IGateUtility
as 参数的构造函数。为什么会这样写?我必须传递的参数是什么。
public class ServiceStation
{
IGateUtility _gateUtility;
public ServiceStation(IGateUtility gateUtility)
{
this._gateUtility = gateUtility;
}
public void OpenForService()
{
_gateUtility.OpenGate();
}
public void DoService()
{
//Check if service station is opened and then
//complete the vehicle service
}
public void CloseForDay()
{
_gateUtility.CloseGate();
}
}
public class ServiceStationUtility : IGateUtility
{
public void OpenGate()
{
//Open the shop if the time is later than 9 AM
}
public void CloseGate()
{
//Close the shop if the time has crossed 6PM
}
}
public interface IGateUtility
{
void OpenGate();
void CloseGate();
}
解决方案
构造函数参数是依赖注入的一个例子,特别是被称为“构造函数注入”的技术(通常是首选技术)。
ServiceStation
不应该包含 a 的逻辑,因为IGateUtility
它与门没有任何关系(单一责任原则)。但是,它确实需要使用门,因此您可以传递一个实现的对象IGateUtility
。
一般来说,我认为在这种情况下继承是没有意义的。但有一条原则规定:
更喜欢组合而不是继承
这基本上意味着;注入(组合)对象以访问它们的行为,而不是从它们继承。
推荐阅读
- python-3.x - Python:在“pywintypes.py SyntaxError:解析时意外 EOF”中导入 Dash 或扭曲结果
- applescript - 为什么在 AppleScript 中设置文件夹和文件的路径不起作用?
- java - 卡在两个矩阵程序的乘法上
- android - 将图像返回到 IMAGE_CAPTURE_INTENT
- antlr - 为什么我的 ANTLR4 解析器语法错误“输入时没有可行的替代方案”?
- python - 颜色图不随 imshow() 改变
- ruby - SSHKit::Runner::ExecuteError:执行为 undefined@undefined 时出现异常:getaddrinfo:ai_socktype 不支持 Servname
- azure - Azure Log Analytics 上的此环境不支持固定到仪表板
- magento2 - 类 adminhtmlConfigScope 不存在 magento 2.4
- netlogo - Netlogo:在行为空间中跨运行保存数据以节省加载时间