Design patterns Tutorial => Static Factory Method C# (original) (raw)
Example
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
- if you want to give a meaningfull name to the method that generates your object.
- if you want to avoid overcomplex object creation see Tuple Msdn.
- if you want to limit the number of objects created (caching)
- if you want to return an object of any subtype of their return type.
There are some disadvantages like
- Classes without a public or protected constructor cannot be initialized in the static factory method.
- Static factory methods are like normal static methods, so they are not distinguishable from other static methods (this may vary from IDE to IDE)
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