我的设备采用主/从配置,我正在开发 WPF/MVVM 应用程序。
我有一个 COM 对象(所有实现 IDevice
的对象)代表外部设备/Modbus 网络的状态并附加到类似 SerialPort
的对象上或 Socket
.这意味着,在通过 Version
识别设备后和 Revision
,我调用IDevice device = DeviceManager.GetDevice(version, revision);
获取表示出厂默认设备状态的对象。
现在我有一个 IDevice
,我可以调用它的 API 来获取类似 List<ushort> GetCoreRegisters()
的东西和 List<ushort> GetAllRegisters()
.话虽如此,在读取寄存器值后,我必须调用 IDevice
的 API 来设置值:device.SetItemValue(registerAddress, registerValue)
以便更新网络另一端设备的状态。
我创建了一个 Master
处理通信层的类型( Socket
与 SerialPort
)。
在我的应用程序的当前状态下,我在我的一个 View 模型中调用类似以下伪代码的内容(单击按钮后):
IDevice device = null;
profile = SelectedProfile
master = MasterFactory.GetMaster(profile.Name)
master.Open() //Connects or Opens SerialPort/Socket
if(master.DeviceCheck(profile.SlaveAddress))
{
KeyValuePair<ushort, ushort> info = await master.IdentifyDeviceAsync(profile.SlaveAddress);
device = DeviceManager.GetDevice(info.Key, info.Value)
initList = device.GetInitializationRegisters()
initValues = await master.ReadRegisters(profile.SlaveAddress, initList)
for(int i = 0; i < initList; i++)
device.SetRegisterValue(initList[i], initValues[i]);
allRegisters = device.GetAllRegisters();
allValues = await master.ReadRegisters(profileSlaveAddress, allRegisters)
for ... repeat
}
if device != null, DevicesInViewModel.Add(device)
master.Close()
我的问题是,这是正确的设计,还是我应该有一个 List<IDevice> Devices
在 Master
在识别设备之后,我会做一些更像是:
device = DeviceManager.GetDevice(info.Key, info.Value);
master.Add(device);
// possibly add more devices if needed
List<IDevice> devices = master.ReadDevices()
if devices != null, DevicesInViewModel.AddRange(devices);
所有GetRegister
和 SetRegisterValue
逻辑在里面 Master
--意思是师父无所不知IDevice
并处理配置从站状态的逻辑。
最佳答案
在理想情况下,查看模型代码非常简单。您当然不希望在其中运行长时间的操作和循环。 View 模型包含用于处理来自 View 的命令的逻辑,仅此而已。
您的第一个示例似乎包含相当多的领域知识和业务逻辑。这应该在模型中某处。据我所知,您的 Master
类似乎是放置它的合理位置。
要回答名义上的问题:主人对他们的奴隶了解很多,当然足以“驱使”或“使用”他们。因此,它知道 IDevice
中的所有内容就可以了。不过要确保它是通用的,主人不应该知道他正在处理的是什么类型的奴隶。
关于c# - 主人对他们的奴隶真正了解多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28706098/