【发布时间】:2017-05-24 05:18:17
【问题描述】:
当我使用工厂模式时,当孩子有额外的属性/方法时,我对如何从中创建子类感到困惑。工厂返回父类型,因为它确定要制作哪个子类,但是当发生这种情况时,我不能像子类一样使用它返回的内容。
public abstract class Factory
{
public abstract Person getPerson(string type);
}
public class PersonFactory : Factory
{
public override Person getPerson(string type) {
switch (type) {
case "admin":
return new Admin();
case "customer":
return new Customer();
default:
return new Admin();
}
}
}
public abstract class Person
{
public abstract string Type { get; }
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
}
public class Admin : Person
{
private string _securityRole;
public Admin()
{
Id = 0;
}
public override string Type
{
get{
return "admin";
}
}
public string SecurityRole
{
get { return _securityRole; }
set { _securityRole = value; }
}
}
所以我的问题是,当我创建一个 PersonFactory 对象并决定使用该工厂来创建其他派生类时。我注意到 getPerson() 返回 Person 而不是实际输入 Admin 或 Customer。如何让工厂创建子类,以便它们实际上是子对象?
Factory pf = new PersonFactory();
Person admin = pf.getPerson("admin");
admin.Id = 1; // is fine
admin.SecurityRole // cannot access
【问题讨论】:
-
看看这段代码,我想知道管理员是否真的应该“成为”一个人——也许它应该是一个人的“角色”。我意识到这段代码可能来自教程或其他东西,但如果它是生产代码,我会考虑 Liskov 替换原则并考虑这是否违反它。 en.wikipedia.org/wiki/Liskov_substitution_principle
标签: c# design-patterns factory