I have a couple of questions related to patterns and if you guys could help, it'd be great.
I have an example of a factory pattern code below (code at bottom)-
The questions I have are -
bool GotLegs()
{
return true; //Always returns true for both People types
}
So if I want to implement this common method for both Villagers as well as CityPeople, is there another pattern that I could implement?
IPeople people = Factory.GetPeople(PeopleType.URBAN);
I understand that static is not an option with interfaces, but just checking to see if there is a way out there.
ACTUAL 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;
}
}
Question 1:
There are several options:
Make GotLegs
an extension method for IPerson
:
public static class PersonExtensions
{
public static bool GotLegs(this IPerson person)
{
return true;
}
}
In that case, IPerson
shouldn't define GotLegs
itself.
Add GotLegs
to the IPerson
interface and create a base class PersonBase
that implements this method and make CityPeople
and Villagers
derive from that base class.
Question 2:
Simple make GetPeople
and Factory
static:
public static class Factory
{
public static IPeople GetPeople(PeopleType type)
{
...
}
}
Usage would be just as you showed:
IPeople people = Factory.GetPeople(PeopleType.URBAN);