I am trying to learn the factory design pattern. I have created a code for creating two animals (for now only dogs and a cats).
I have got an Animal (as a product)
public abstract class Animal
{
public abstract void CreateBody();
public abstract void CreateLeg();
}
Dog and Cat Implements Animal class:
public class Dog: Animal
{
public override void CreateBody()
{
Console.WriteLine("Dog body created");
}
public override void CreateLeg()
{
Console.WriteLine("Dog body created");
}
}
Cat Implements Animal:
public class Cat: Animal
{
public override void CreateBody()
{
Console.WriteLine("Cat body created");
}
public override void CreateLeg()
{
Console.WriteLine("Cat Leg created");
}
}
Created a factory class that makes different animal according to the input given in the parameter:
public class AnimalFactory
{
public static Animal CreateAnimal(string animal)
{
Animal animalDetails = null;
if (animal == "cat")
{
animalDetails = new Cat();
}
else if (animal == "dog")
{
animalDetails = new Dog();
}
animalDetails.CreateBody();
animalDetails.CreateLeg();
return animalDetails;
}
}
In the main it is used as:
static void Main(string[] args)
{
Animal animalDetails = AnimalFactory.CreateAnimal("cat");
if (animalDetails != null)
{
}
else
{
Console.Write("Invalid Card Type");
}
Console.ReadLine();
}
Here in this code, I know exactly what methods I need to call to create an animal, so I called those methods in the factory class.
As I read in the various tutorials and books, most of the implementation of the factory method uses another concrete factory method to create the concrete product?
In what case it is appropriate to create the concrete factory method? Is that concrete factory relevant in this demo too?