我有幾個與模式有關的問題,如果你們能幫忙,那會很棒。
我有下面工廠模式的代碼(在底部代碼)的一個例子 -
的問題,我是 -
具有通用功能的方法的工廠模式
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