Factory design pattern; parent = new child()(工厂设计模式;父项=新子项())
本文介绍了工厂设计模式;父项=新子项()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用工厂模式时,当孩子有额外的属性/方法时,我不知道如何从它生成子类。工厂在确定要创建哪个子类时返回父类型,但当发生这种情况时,我不能像使用子类那样使用它返回的内容。
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
推荐答案
快速解决方案
Admin admin = (Admin)pf.getPerson("admin");
但更好的实施是
1)对工厂类使用静态方法。
2)使用泛型和接口。您的新代码将为:
public class PersonFactory //: Factory
{
public static T getPerson<T>() where T: IPerson
{
return Activator.CreateInstance<T>();
}
}
public interface IPerson
{
string Type { get; }
int Id { get; set; }
}
public class Admin : IPerson
{
private string _securityRole;
public Admin()
{
Id = 0;
}
public string Type
{
get
{
return "admin";
}
}
public string SecurityRole
{
get { return _securityRole; }
set { _securityRole = value; }
}
public int Id
{
get;set;
}
}
public class Customer : IPerson
{
private string _securityRole;
public Customer()
{
Id = 0;
}
public string Type
{
get
{
return "customer";
}
}
public string SecurityRole
{
get { return _securityRole; }
set { _securityRole = value; }
}
public int Id
{
get;set;
}
}
及使用方法:
Admin a = PersonFactory.getPerson<Admin>();
Customer b = PersonFactory.getPerson<Customer>();
这篇关于工厂设计模式;父项=新子项()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:工厂设计模式;父项=新子项()
基础教程推荐
猜你喜欢
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
