我有一个便于发现HID
设备的类,当检测到设备时,event
被引发并随后被另一个类检测到,该类将最终负责创建{object
1}}代表HID
设备。 creation class
使用新创建的event
对象引发自己的HID
。
考虑到这一点,我有几个设计查询:
1) 我已经对" 最佳实践" 进行了一些研究,关于在运行时创建未知数量或类型的对象
Abstract Factory
设计模式经常使用在结果中。Abstract Factory
设计模式是否适合我所拥有的场景,或者我还应该做些什么呢?2)
HidFinder
类引发一个事件以通知那些感兴趣的人(主要是HidCreator
类)已发现设备。然后,HidCreator
类会引发一个包含新创建的HID
设备的事件。这似乎是正确的方法,但是,无论哪种方式确认都会受到赞赏。
下面是相关代码的一个愚蠢的例子。
public class HidFinder
{
public event EventHandler<HidFoundArgs> HidFoundHandler;
private void DeviceAdded(object sender, EventArrivedEventArgs e)
{
OnHidFoundHandler(new HidFoundArgs());
}
protected virtual void OnHidFoundHandler(HidFoundArgs e)
{
EventHandler<HidFoundArgs> handler = this.HidFoundHandler;
if (handler != null)
{
handler(this, e);
}
}
}
public class HidCreator
{
private readonly HidFinder hidFinder;
public event EventHandler<IHidDevice> HidDeviceCreatedHandler;
public HidCreator(HidFinder hidFinder)
{
this.hidFinder = hidFinder;
this.hidFinder.HidFoundHandler += HidFinderOnHidFoundHandler;
}
private void HidFinderOnHidFoundHandler(object sender, HidFoundArgs hidFoundArgs)
{
// Create a new HID
var newHidDevice = Factory.CreateMethod();
OnHidDeviceCreatedHandler(newHidDevice);
}
protected virtual void OnHidDeviceCreatedHandler(IHidDevice e)
{
EventHandler<IHidDevice> handler = this.HidDeviceCreatedHandler;
if (handler != null)
{
handler(this, e);
}
}
}
答案 0 :(得分:0)
它通常看起来很好,但我会做两处修改:
Factory
似乎是一个全局对象,最好使用依赖注入,例如更好的单元测试。Factory.CreateMethod
以使用参数,因为我们不知道将创建IHidDevice
的具体实施方式,以及我们是否需要HidFoundArgs
更改后的代码:
public class HidCreator
{
private readonly HidFinder hidFinder;
private readonly IHidDeviceFactory factory;
public event EventHandler<IHidDevice> HidDeviceCreatedHandler;
public HidCreator(IHidDeviceFactory factory, HidFinder hidFinder)
{
this.factory = factory;
this.hidFinder = hidFinder;
this.hidFinder.HidFoundHandler += HidFinderOnHidFoundHandler;
}
private void HidFinderOnHidFoundHandler(object sender, HidFoundArgs hidFoundArgs)
{
// Create a new HID
var newHidDevice = factory.Create(HidFoundArgs.ToCreationParameters(hidFoundArgs));
OnHidDeviceCreatedHandler(newHidDevice);
}
protected virtual void OnHidDeviceCreatedHandler(IHidDevice e)
{
EventHandler<IHidDevice> handler = this.HidDeviceCreatedHandler;
if (handler != null)
{
handler(this, e);
}
}
}
public interface IHidDeviceFactory
{
IHidDevice Create(HidCreationParameters parameters);
...
}
public class HidCreationParameters
{
...
}
public class HidFoundArgs
{
public static HidCreationParameters ToCreationParameters(HidFoundArgs args)
{
...
}
}