我目前正在开发一个机器人,并且有大约 8 个用于不同对话框的单独类(都在同一个命名空间中!)。它们都包含不同的任务,因此我遇到了一个小问题。我想知道最佳实践是什么:使用接口,使用工厂模式……然而,所有这些选项都迫使我使用内部方法。(我通过接口得到它,因为你承诺某些行为,但是对于工厂模式我真的不知道 - 老实说......)因为没有特定方法的定义 - 但这意味着我必须做出很多这些内部方法,我试图避免冗余。
首先我只是实例化了一个新对象,但我很快意识到这意味着每次调用机器人时都会创建一个各种类型/对话框的新对象——这不是很有效,对吧?我也尝试在构造函数中实例化它们,但这迫使我使用接口,这给我带来了与我之前所说的相同的问题。我也研究了部分类,但我不确定使用 8 个部分类是否真的......好吗?
现在我正在用这段代码尝试工厂模式:(感谢这个线程:How to prevent an instance of an object in c#)
public class DialogFactory
{
private NameDialog _nameDialog;
private CertificateDialog _certificateDialog;
private ProfileDialog _profileDialog;
private ClassDialog _classDialog;
private LocationDialog _locationDialog;
private SkillDialog _skillDialog;
private EducationDialog _educationDialog;
private SpecializationDialog _specializationDialog;
public DialogFactory CreateDialog(string dialog)
{
switch (dialog.ToLower())
{
case "name": return new NameDialog();
case "certificate": return new CertificateDialog();
case "profile": return new ProfileDialog();
case "class": return new ClassDialog();
case "location": return new LocationDialog();
case "skill": return new SkillDialog();
case "education": return new EducationDialog();
case "specialization": return new SpecializationDialog();
default: throw new Exception("That dialog does not exist.");
}
throw new Exception("That dialog does not exist.");
}
}
为了给出对话框看起来的一些上下文,我还将在此处添加名称对话框:
public class NameDialog : DialogFactory
{
ProfileService profileService = new ProfileService();
public async Task AddNameResponse(ITurnContext turnContext, Profile profile, string value { … }
}
我尝试在主方法中访问 AddNameResponse 任务,如下所示:await dialog.CreateDialog("name").AddNameResponse(turnContext, profile, value);
这不被接受,但是给了我以下警告:“DialogFactory”不包含“AddNameResponse”的定义,并且没有可访问的扩展方法“AddNameResponse”接受第一个参数'对话工厂'。修复将是一个内部任务,但我试图避免这种情况(之前给出的原因)。
我真的很茫然,因为我不知道最佳做法是什么。我正在尝试制作我可以制作的最有效和最干净的代码,并避免冗余并尽可能多地使用松散耦合 - 但我不知道如何在这种情况下实现这一点......我希望我已经制定了我的问题足够好(也是问题)!