0

我必须如何更新一个只能从另一个特定类更新的类?

在以下示例中,封装被破坏,因为Sensor可以从任何其他类更新,而不仅仅是从Device. 我对吗?

class Device
{
    public IEnumerable<Sensor> Sensors { get; private set; }

    void SomeInternalCall(int sensorId, int signal)
    {
        Sensors.First(s => s.Id == sensorId).Update(signal);
    }

}

class Sensor
{
    public int Id { get; private set; }

    public event Action<int> OnSignal;

    public void Update(int signal)
    {
        if (OnSignal != null) OnSignal(signal);
    }
}

class SensorUser
{
    public SensorUser(Sensor s)
    {
        s.OnSignal += SignalHandler;
    }

    void SignalHandler(int signal)
    {
        // ...
    }
}
4

1 回答 1

1

您可以创建一个提供只读访问权限的接口并将其提供给SensorUser,同时SensorDevice.

interface ISensor
{
    int Id { get;  }    
    event Action<int> OnSignal;
}

class Sensor : ISensor
{
    public int Id { get; private set; }    
    public event Action<int> OnSignal;

    public void Update(int signal)
    {
        if (OnSignal != null) OnSignal(signal);
    }
}

class SensorUser
{
    public SensorUser(ISensor s)
    {
        s.OnSignal += SignalHandler;
    }    
}
于 2013-04-19T15:11:10.517 回答