的最佳方法是什么:
假设我有一个名为 Person
的类和许多针对专业人员的派生类。
假设在我的应用程序开始时,我知道我必须与一个人打交道,但直到很久以后我才知道它是什么样的人(这超出了我的控制范围,所以我无法确定开始时的人员类型)。
因此,在开始时,我将创建一个Person
并为其填充属性。后来,当我知道它是什么样的Person
时,我会实例化一个专门的人并为她复制任何保存的属性。
有没有更优雅的方法可以在不创建两个对象的情况下做到这一点?
不知道人员的类型,您将无法避免实例化两个对象。 在你了解专门的人员之前,必须有一些东西来包含基本Person
属性,但是如果不稍后实例化专用对象,你就不能利用多态性。
一种选择是使用组合模式,其中每个专业人员都包含一个 Person 实例,而不是从中继承。 您仍然需要实例化两个对象,但不必每次都重写代码来复制保存的属性。 下面是一个示例(C# 语法):
public interface IPerson
{
string Name { get; }
int Age { get; }
}
public class Person : IPerson
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public abstract class SpecialPersonBase : IPerson
{
private IPerson myPerson;
protected SpecialPersonBase(IPerson person)
{
myPerson = person;
}
public string Name { get { return myPerson.Name; } }
public int Age { get { return myPerson.Age; } }
public abstract string Greet();
}
public class Doctor : SpecialPersonBase
{
public Doctor(IPerson person) : base(person) { }
public override string Greet()
{
return "How are you feeling?";
}
}
public class Accountant : SpecialPersonBase
{
public Accountant(IPerson person) : base(person) { }
public override string Greet()
{
return "How are your finances?";
}
}
您可以像这样使用这些类:
IPerson bob = new Person("Bob", "25");
// Do things with the generic object
// until you can determine the specific type
SpecialPerson specialBob;
if (bobIsDoctor)
{
specialBob = new Doctor(bob);
}
else if (bobisAccountant)
{
specialBob = new Accountant(bob);
}
specialBob.Greet();