我有几个与模式有关的问题,如果你们能帮忙,那会很棒。
我有下面工厂模式的代码(在底部代码)的一个例子 -
的问题,我是 -
具有通用功能的方法的工厂模式
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;
}
}
所以,如果我从问题1执行选项2,然后我会为虚拟申报GotLegs(),然后在子类中重写 - 村及CityPeople,是否正确? 感谢Daniel的回应! – snakepitbean 2013-04-26 17:10:27
@snakepitbean:如果你真的想在子类中覆盖它,你只需要声明它是虚拟的。如果你不想重写它 - 这就是我从你的问题中了解到的 - 使它变成虚拟是没有必要的。 – 2013-04-26 18:08:42
对不起丹尼尔我的意思是反过来。 GetName()[不常见]的方法将成为“PeopleBase”类中的一个抽象方法,并将在相应的类Village&CityPeople中实现,对吗? – snakepitbean 2013-04-26 18:31:28