如何更新必须仅从其他特定类更新的类?
在以下示例中,封装被破坏,因为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)
{
// ...
}
}
答案 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;
}
}