首页 > 解决方案 > 没有完全理解为什么我会在一个类中有一个接口,而不是从它继承

问题描述

我正在查看 SOLID 原则,并发现了一些 SRP 代码。

我有这段代码,但我不知道为什么我会有一个接口,以我在下面的方式声明?这对我有什么好处?我在这里找到,它显示了一个解决方案,但它并没有真正解释代码如何更好地工作或为什么事情是这样的。

我不明白的是:

IGateUtility _gateUtility;public class ServiceStation, 和它的正下方是带有IGateUtilityas 参数的构造函数。为什么会这样写?我必须传递的参数是什么。

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();
}

标签: c#interface

解决方案


构造函数参数是依赖注入的一个例子,特别是被称为“构造函数注入”的技术(通常是首选技术)。

ServiceStation不应该包含 a 的逻辑,因为IGateUtility它与门没有任何关系(单一责任原则)。但是,它确实需要使用门,因此您可以传递一个实现的对象IGateUtility

一般来说,我认为在这种情况下继承是没有意义的。但有一条原则规定:

更喜欢组合而不是继承

这基本上意味着;注入(组合)对象以访问它们的行为,而不是从它们继承。


推荐阅读