返回类型的织物图案方法

问题描述 投票:0回答:4

我是.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()实例类。

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

c# .net design-patterns factory-pattern
4个回答
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;
    }

}

例如上面 - Employee类实际上也是一个Person,因为它继承自抽象类(它实际上没有实现抽象类中的任何东西,因为没有任何东西可以实现)

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


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
投票

因为Pilot继承自Person。


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.