从另一个类更新类,封装问题

时间:2013-04-19 15:08:13

标签: c# design-patterns encapsulation

如何更新必须仅从其他特定类更新的类?

在以下示例中,封装被破坏,因为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)
    {
        // ...
    }
}

1 个答案:

答案 0 :(得分:1)

您可以创建一个提供只读访问权限的界面,并将其提供给SensorUser,同时在Sensor中拥有Device个实例的集合。

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