mercredi 21 septembre 2016

Factory to create different objects of same interface

I have 1 interface:

public interface ISummary
{
   int EventId {get; set;}
}

And many concrete classes that implement this interface:

public class EmployeeSummary : ISummary
{
   public int EventId {get; set;},
   public int TotalUniqueCount {get; set;}
   public int Location {get; set;}
}

public class CarSummary : ISummary
{
   public int EventId {get; set;}
   public int TotalMiles {get; set;}
   public int TotalHours {get; set;}
}

etc....

The only shared property is the EventId. Is there a way to have 1 factory method that creates all of these summary objects? I want 1 entry point which decides which objects to create.

So something like:

public ISummary CreateSummary(ConcreteObjectType with properties)
{
if EmployeeSummary
 --Call this method to create and return EmployeeSummary

if CarSummary
 --Call this method create and return CarSummary
}

I want all calls within other classes to call this method rather than creating the objects themselves. The part I am struggling with is how do I pass the properties to assign to the objects to this CreateSummary method since all the properties on the objects will be different? I am open to changing the objects at this point at well if there is a better design pattern I should be using here.

Aucun commentaire:

Enregistrer un commentaire