C#中工厂的构造函数参数,我做得对吗
本文关键字:参数 工厂 构造函数 | 更新日期: 2023-09-27 18:35:53
我在下面解释了我的问题,我的问题是:1. 我使用工厂模式来解决这个问题是否正确2. 我做得对吗?
我有一个你可以称之为事件跟踪系统,由工人/经理在建筑工地上使用,它是在 ASP.NET MVC中开发的,该应用程序存储在不同位置发生的不同类型的事件。现在,我必须为用户提供一种根据位置,事件类型等生成报告的方法。
这就是我在代码中的做法(为了简洁起见,在某些部分包含注释而不是代码)-
//Controller methods
public ActionResult ReportByLocation(){
var incidents = GetDataFromRepo();
var reportFactory = new IncidentReportFactory(incidents, "ByLocation");
var pdfView = new ReportsGenerator(reportFactory).GetPdfView();
return pdfView;
}
public ActionResult ReportByType(){
var incidents = GetDataFromRepo();
var reportFactory = new IncidentReportFactory(incidents, "ByType");
var pdfView = new ReportsGenerator(reportFactory).GetPdfView();
return pdfView;
}
//Concrete factory class
public class IncidentReportFactory : ReportFactory{
public IncidentFactory(List<Incident> incidents, string reportType){
//Initialize properties
}
public ConcreteReport CreateConcreteReport(){
switch(ReportType){
case "ByLocation": return new IncidentLocationReport(incidents);
break;
case "ByType": return new IncidentTypeReport(incidents);
break;
}
}
}
//ConcreteReport class
public class IncidentLocationReport : ConcreteReport{
public IncidentLocationReport(List<Incident> incidents){
//Constructor which sorts, splits, etc. based on location
//and returns
}
}
//Report generator class
public ReportsGenerator{
public ReportsGenerator(ReportFactory factory){
Factory = factory;
}
public PDFView GetPdfView(){
var report = factory.CreateConcreteReport();
var pdfView = ConstructPdfWithAllFormatting(report);
return pdfView;
}
}
另请注意,我继承自抽象工厂和具体类我的代码有意义吗?还是我做错了?请指出我正确的方向。谢谢!
基本上你是对的。
您具有具有 metohd 的类IncidentReportFactory
CreateConcreteReport
它创建了ConcreteReport
对象取决于reportType
从抽象类继承是我的观点不是。 您的ReportFactory
抽象类没有方法,因此不需要使用它。它是低抽象时不是方法女巫可以通过共享。让接口这样做是件好事。
public interface IIncidentReportFactory
{
public IConcreteReport CreateConcreteReport();
}
和实现:
public class IncidentReportFactory : IIncidentReportFactory
{
public IncidentFactory(List<Incident> incidents, string reportType)
{
//Initialize properties
}
public ConcreteReport CreateConcreteReport()
{
switch(this.ReportType)
{
case "ByLocation": return new IncidentLocationReport(incidents);
break;
case "ByType": return new IncidentTypeReport(incidents);
break;
}
return null //no match
}
此外,您必须更改一些名称:
var reportFactory = new IncidentReportFactory(incidents, "ByLocation");
reportFactory
是非常误解的名字。不是reportFactory
是ConcreteReport
对象。
当您将抽象类更改为接口时,ReportsGenerator
类应该像这样
//Report generator class
public ReportsGenerator{
public ReportsGenerator(IConcreteReport concreteReport){
this.concreteReport= concreteReport;
}
public PDFView GetPdfView(){
var pdfView = ConstructPdfWithAllFormatting(this.concreteReport);
return pdfView;
}
}
使用依赖注入容器也是一个很好的做法