I was a bit able to understand Factory Pattern and came up with this implementation.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the fruit name to get the Fruit!");
string fruit = Console.ReadLine();
FruitsList fruits;
if (Enum.TryParse(fruit, true, out fruits))
{
var fruitWeight = GetFruitWeight(fruits);
Console.ReadLine();
}
else
{
Console.WriteLine("Fruit Name is undefined!");
Console.ReadLine();
}
}
private static object GetFruitWeight(FruitsList fruitNumber)
{
switch (fruitNumber)
{
case FruitsList.Banana:
return new Banana();
case FruitsList.Apple:
return new Apple();
}
return null;
}
}
internal class Banana : IFruits
{
public float ReturnFruitWeight()
{
return (float)10.00;
}
}
public interface IFruits
{
float ReturnFruitWeight();
}
public class Apple : IFruits
{
public float ReturnFruitWeight()
{
return (float)30.00;
}
}
public enum FruitsList
{
Apple,
Banana,
}
The whole idea of mine (from the theoretical understanding) is that the GetFruitWeights function shall accept an enum type and then return the fruit weight. I was able to get the object of a particular Fruit but now stuck up with how from the Fruit object, I get the weight of the fruit.
Also, to add to my doubts list, Am I really following Factory pattern in this implementation? And also, some materials in the internet uses an abstract class too ? What should I follow ? A interface implementation or should I use an abstract class and override it ?
Thanks in advance for your help.