I get the idea of factory method pattern, but I feel that in some situations, is it necessary to use this pattern? For example, below is some code that use factory method;
public interface IAnimal
{
void Speak();
void Action();
}
public class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Dog says: Bow-Wow.");
}
public void Action()
{
Console.WriteLine("Dogs prefer barking...\n");
}
}
public class Tiger : IAnimal
{
public void Speak()
{
Console.WriteLine("Tiger says: Halum.");
}
public void Action()
{
Console.WriteLine("Tigers prefer hunting...\n");
}
}
public abstract class IAnimalFactory
{
public abstract IAnimal CreateAnimal();
}
public class TigerFactory : IAnimalFactory
{
public override IAnimal CreateAnimal()
{
return new Tiger();
}
}
public class DogFactory : IAnimalFactory
{
public override IAnimal CreateAnimal()
{
return new Dog();
}
}
and client can invoke:
IAnimalFactory tigerFactory = new TigerFactory();
IAnimal aTiger = tigerFactory.MakeAnimal();
aTiger.Speak();
aTiger.Action();
Below is my questions:
Q1- Client can also do like:
IAnimal aTiger = new Tiger();
aTiger.Speak();
aTiger.Action();
so why takes extra steps to define and use abstract factory and concrete factories?
Q2-can IAnimalFactory
be defined as an interface instead of abstract classess?
Q3-What's the official name of IAnimalFactory
? is it called "abstract factory"?
Aucun commentaire:
Enregistrer un commentaire