I'm learning Factory pattern and I've implemented this simple example of an abstract factory. I've followed this video a little bit while writing this small example. Is there anything anti-pattern or wrong in this example?
I've created two different Pizzas
public interface IPizza
{
public string Name { get; set; }
}
public class NewYorkPizza : IPizza
{
public string Name { get; set; } = "NewYork Pizza";
}
public class ItalianPizza : IPizza
{
public string Name { get; set; } = "Italian Pizza";
}
Then relevant Pizza factories
public interface IPizzaFactory
{
IPizza Create();
}
public class NewYorkPizzaFactory : IPizzaFactory
{
public IPizza Create()
{
return new NewYorkPizza();
}
}
public class ItalianPizzaFactory : IPizzaFactory
{
public IPizza Create()
{
return new ItalianPizza();
}
}
Then created an abstract factory
public interface IAbstractPizzaFactory
{
IPizzaFactory GetNewYorkPizzaFactory();
IPizzaFactory GetItalianPizzaFactory();
}
public class AbstractPizzaFactory : IAbstractPizzaFactory
{
public IPizzaFactory GetNewYorkPizzaFactory()
{
return new NewYorkPizzaFactory();
}
public IPizzaFactory GetItalianPizzaFactory()
{
return new NewYorkPizzaFactory();
}
}
Notice that I'm avoiding
abstract
class way and using only Interface to achieve kind of same thing and although, it looks correct to me, but I'm confuse here if it's the right approach or not?
And then I can use it like this
public class Test
{
private readonly IAbstractPizzaFactory _abstractPizzaFactory;
public Test(IAbstractPizzaFactory abstractPizzaFactory)
{
_abstractPizzaFactory = abstractPizzaFactory;
}
private void CreatePizza()
{
IPizza newYorkPizza = _abstractPizzaFactory.GetNewYorkPizzaFactory().Create();
Console.WriteLine(newYorkPizza.Name);
IPizza italianPizza = _abstractPizzaFactory.GetItalianPizzaFactory().Create();
Console.WriteLine(italianPizza.Name);
}
}