Search code examples
c#.netdesign-patternsfactory-pattern

Return type of fabric pattern method


I am a beginner in .net. I'm trying to understand the fabric pattern method.

I found this code example:

   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";

I can't understand CreatePerson method in this example.

public static Person CreatePerson(string typeOfPerson)
    {
        switch (typeOfPerson)
        {
            case "Employee":
                return new Employee();
            case "Pilot":
                return new Pilot();
            default:
                return new Employee();
        }
    }

The method returns Person type, but in switch operator as you can see it's creates and returns Pilot() or Employee() instance class.

How can this be that the return type definitions in the method's signature is different from the return type of the function itself.


Solution

  • Because all of these return types inherit from Person. You can implicitly return a derived class from a function.

    public class Employee : Person <------ this Employee is inheriting the abstract class 'Person' (but not implementing anything from it)
    {
        public Employee()
        {
            this.Salary = 20000;
        }
    
    }
    

    e.g. above - the Employee class is actually a Person too since it inherits from the abstract class (it actually doesn't implement anything from the abstract class as there is nothing to implement)

    The Person class here is abstract yet it doesn't specify any abstract members - is this just test code?