返回类型的织物图案方法

时间:2012-07-12 13:03:06

标签: c# .net design-patterns factory-pattern

我是.net的初学者。我正在尝试了解面料图案方法。

我找到了这段代码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();
        }
    }
}

并使用工厂:

Person thePilot = PersonFactory.CreatePerson("Pilot");
    ((Pilot)thePilot).PilotNumber = "123ABC";

在这个例子中,我无法理解CreatePerson方法。

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

该方法返回Person类型,但在switch运算符中,您可以看到它创建并返回Pilot()或Employee()实例类。

这怎么可能是方法签名中的返回类型定义与函数本身的返回类型不同。

4 个答案:

答案 0 :(得分:3)

将工厂方法更新为通用方法时要容易得多。像这样。

public static TPerson CreatePerson<TPerson>() where TPerson: Person {
    if (typeof(TPerson) == typeof(Employee)) {
        return new Employee();
    } else if (typeof(TPerson) == typeof(Pilot)) {
        return new Pilot();
    } else {
        return new Employee();
    }
}

然后你可以在没有任何演员的情况下使用它:

Pilot pilot = PersonFactory.CreatePerson<Pilot>();
pilot.PilotNumber = "123ABC";

答案 1 :(得分:2)

因为所有这些返回类型都继承自Person。您可以隐式返回函数中的派生类。

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。上面 - Employee类实际上也是一个Person,因为它继承自抽象类(它实际上没有实现抽象类中的任何东西,因为没有任何东西可以实现)

此处的Person类是抽象的,但它没有指定任何抽象成员 - 这只是测试代码吗?

答案 2 :(得分:1)

因为Pilot继承自Person。

答案 3 :(得分:1)

Employee和Pilot类是人的子类派生类。在OOP中,这与关系类似。员工是一个人,一名飞行员是一个人,所以返回其中一种类型是完全合法的。调用者不会知道(不使用反射)它回来的人的类型,并且不应该关心。