我有几个与模式相关的问题,如果你们可以提供帮助,那就太好了。
我有一个下面的工厂模式代码示例(底部的代码) -
我的问题是 -
bool GotLegs()
{
return true; //Always returns true for both People types
}
因此,如果我想为村民和CityPeople实施这种常用方法,我可以实现另一种模式吗?
IPeople people = Factory.GetPeople(PeopleType.URBAN);
我知道static不是接口的选项,只是检查是否有方法。
实际C#CONSOLE REFERENCE CODE -
//Main Prog
class Program
{
static void Main(string[] args)
{
Factory fact = new Factory();
IPeople people = fact.GetPeople(PeopleType.URBAN);
}
}
//Empty vocabulary of Actual object
public interface IPeople
{
string GetName();
}
public class Villagers : IPeople
{
#region IPeople Members
public string GetName()
{
return "Village Guy";
}
#endregion
}
public class CityPeople : IPeople
{
#region IPeople Members
public string GetName()
{
return "City Guy";
}
#endregion
}
public enum PeopleType
{
RURAL,
URBAN
}
/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{
public IPeople GetPeople(PeopleType type)
{
IPeople people = null;
switch (type)
{
case PeopleType.RURAL:
people = new Villagers();
break;
case PeopleType.URBAN:
people = new CityPeople();
break;
default:
break;
}
return people;
}
}
答案 0 :(得分:2)
问题1:
有几种选择:
将GotLegs
作为IPerson
的扩展方法:
public static class PersonExtensions
{
public static bool GotLegs(this IPerson person)
{
return true;
}
}
在这种情况下,IPerson
不应定义GotLegs
本身。
将GotLegs
添加到IPerson
界面,并创建一个实现此方法的基类PersonBase
,并使CityPeople
和Villagers
派生自该GetPeople
基类。
问题2:
简单制作Factory
和public static class Factory
{
public static IPeople GetPeople(PeopleType type)
{
...
}
}
静态:
IPeople people = Factory.GetPeople(PeopleType.URBAN);
用法就像你展示的那样:
{{1}}
答案 1 :(得分:0)
如果要添加常用功能,可以使用抽象类而不是接口。 在你的情况下,它将是:
public abstract class People
{
public bool GotLegs()
{
return true; //Always returns true for both People types
}
public abstract string GetName();
}
public class CityPeople : People
{
#region IPeople Members
public override string GetName()
{
return "City Guy";
}
#endregion
}
public class Villagers : People
{
#region IPeople Members
public override string GetName()
{
return "Village Guy";
}
#endregion
}