I’m having a hard time figuring out how to implement a factory pattern in a DTO mapper I’m trying to create. I’m pretty sure I need to rethink my design. Here is a very small example of what I’m running in to:
public abstract class Person
{
public string Name { get; set; }
public decimal Salary { get; set; }
}
public class Employee : Person
{
public Employee()
{
this.Salary = 20000;
}
}
public class Pilot : Person
{
public string PilotNumber { get; set; }
public Pilot()
{
this.Salary = 50000;
}
}
public static class PersonFactory
{
public static Person CreatePerson(string typeOfPerson)
{
switch (typeOfPerson)
{
case "Employee":
return new Employee();
case "Pilot":
return new Pilot();
default:
return new Employee();
}
}
}
and to use the factory:
Person thePilot = PersonFactory.CreatePerson("Pilot");
((Pilot)thePilot).PilotNumber = "123ABC";
How do I get around loading the pilot number without typecasting it to Pilot?? is this the wrong way to do this? I could put the pilot number in the Person class, but then Employee would inherit the number and that’s not what I want. What can I do?
Thanks!
-Jackson
You could add methods for specific types to your PersonFactory class, or add a generic
CreatePerson<T>()method, but that would only be useful if the caller already knows what type of person it should be receiving. Maybe this is the case, or maybe not.With this scenario, I’d expect that the code that is actually making the call to PersonFactory.CreatePerson would not know or care what kind of person is being returned. If you have some code after that point that already knows or figures out what type of person object you have, then you will simply have to cast it.
Below is a code example that illustrates what you could do on your factory and different usage scenarios, attempting to explain when you simply need to cast or when you don’t.