The static factory method is a variation of the factory method pattern. It is used to create objects without having to call the constructor yourself.
When to use the Static Factory Method
There are some disadvantages like
Example
Pizza.cs
public class Pizza
{
public int SizeDiameterCM
{
get;
private set;
}
private Pizza()
{
SizeDiameterCM = 25;
}
public static Pizza GetPizza()
{
return new Pizza();
}
public static Pizza GetLargePizza()
{
return new Pizza()
{
SizeDiameterCM = 35
};
}
public static Pizza GetSmallPizza()
{
return new Pizza()
{
SizeDiameterCM = 28
};
}
public override string ToString()
{
return String.Format("A Pizza with a diameter of {0} cm",SizeDiameterCM);
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
var pizzaNormal = Pizza.GetPizza();
var pizzaLarge = Pizza.GetLargePizza();
var pizzaSmall = Pizza.GetSmallPizza();
String pizzaString = String.Format("{0} and {1} and {2}",pizzaSmall.ToString(), pizzaNormal.ToString(), pizzaLarge.ToString());
Console.WriteLine(pizzaString);
}
}
Output
A Pizza with a diameter of 28 cm and A Pizza with a diameter of 25 cm and A Pizza with a diameter of 35 cm