我正在创建一个票务系统,用户提交请求并最终由SME回答。可以在此系统中进行两种类型的请求; SupportHardwareEnquiry和AlternateDriverEnquiry。
由于它们具有相似的特征,我创建了一个名为IRequest的接口
public interface IRequest
{
int RequestId { get; }
State State { get; }
RequestHeader RequestHeader { get; }
InterimDialogue InterimDialogue { get; }
RequestSolution RequestSolution { get; }
}
两种请求类型略有不同,我创建了两个独立的接口,它们都实现了IRequest。
SupportHardwareEnquiry的界面如下所示
public interface ISupportHardwareEnquiry : IRequest
{
SupportingInformation SupportingInformation { get; }
ProblemTask ProblemTask { get; }
}
最后,具体类实现了ISupportHardwareEnquiry
public class SupportHardwareEnquiry : ISupportHardwareEnquiry
{
public int RequestId { get; private set; }
public State State { get; private set; }
public RequestHeader RequestHeader { get; private set; }
public SupportingInformation SupportingInformation { get; private set; }
public ProblemTask ProblemTask { get; private set; }
public InterimDialogue InterimDialogue { get; private set; }
public RequestSolution RequestSolution { get; private set; }
// etc ...
}
要实例化SupportHardwareEnquiry对象,已使用RequestFactory
public class RequestFactory : IRequestFactory
{
public IRequest CreateSupportHardwareEnquiry()
{
return new SupportHardwareEnquiry();
}
public IRequest CreateAlternateDriverEnquiry()
{
return new AlternateDriverEnquiry();
}
}
我还使用存储库列出请求,并重新构建单个请求。
public interface IRequestRepository
{
IEnumerable<IRequest> GetAllRequests();
IRequest GetAlternateDriverEnquiry(int id);
IRequest GetSupportHardwareEnquiry(int id);
}
虽然我可以使用GetAllRequests()方法,因为它只依赖于RequestHeader中的信息,但我遇到的问题是在使用我的RequestFactory或Repository来实例化或重构单个对象时。
因为他们返回了IRequest,所以我无法访问SupportHardwareEnquiry(即SupportingInformation和ProblemTask)的属性。
我可以投射到具体类型:
IRequest supportHardwareEnquiry = factory.CreateSupportHardwareEnquiry();
var request = (SupportHardwareEnquiry)supportHardwareEnquiry;
但现在看到我需要提前知道的事情,我希望得到的回报,其余部分似乎没什么意义。
我知道我可以使用继承代替,但是当有时我想将它们视为一般请求时,我应该如何处理这些设计情况,有时候会将其视为特定类型的请求?
答案 0 :(得分:0)
如果CreateSupportHardwareEnquiry()始终返回ISupportHardwareEnquiry,只需在方法定义中键入提示即可。
public class RequestFactory : IRequestFactory
{
public ISupportHardwareEnquiry CreateSupportHardwareEnquiry()
{
return new SupportHardwareEnquiry();
}
public IRequest CreateAlternateDriverEnquiry()
{
return new AlternateDriverEnquiry();
}
}