mardi 23 février 2016

Constructor arguments for Factory in C#, am I doing it right?

I have explained my problem below, my question is: 1. Whether I'm right in using factory pattern to this problem 2. Am I doing it right?

I have what you can call an incident tracker system which is used in construction sites by workers/managers, it's developed in ASP.NET MVC, the application stores different types of incidents that occurred at different locations. Now I have to provide a way for the user to generate reports based on locations, incident type etc.

This is how I'm doing it in my code (have included comments instead of code in some parts for brevity) -

//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;
     }
}

Also note that I'm inheriting from abstract factory and concrete classes Does my code makes any sense? Or am I doing it all wrong? Please point me in the right direction. Thanks!

Aucun commentaire:

Enregistrer un commentaire