我有几个与模式有关的问题,如果你们能提供帮助,那就太好了。
我在下面有一个工厂模式代码的示例(底部的代码)-
我的问题是-
bool GotLegs()
{
return true; //Always returns true for both People types
}
所以如果我想为村民和城市人实现这个通用方法,我可以实现另一种模式吗?
IPeople people = Factory.GetPeople(PeopleType.URBAN);
我知道静态不是接口的选项,而只是检查是否有出路。
实际的 C# 控制台参考代码 -
//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;
}
}