A Simple Factory pattern is one that returns an instance of one of several possible classes, depending on the data provided to it. Usually all of the classes it returns have a common parent class and common methods, but each of them performs a task differently and is optimized for different kinds of data.
public abstract class Travel
{
public abstract decimal GetPrice();
public enum Types
{
Air, Hotel, Car
}
/// <summary>
/// This class return value using factory
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static Travel TravelFactory(Types t)
{
switch (t)
{
case Types.Air:
return new Air();
case Types.Hotel:
return new Hotel();
case Types.Car:
return new Car();
}
throw new System.NotSupportedException("The Travel type " + t.ToString() + " is not recognized.");
}
}
public class Air : Travel
{
private decimal m_Price = 23.5M;
public override decimal GetPrice() { return m_Price; }
}
public class Hotel : Travel
{
private decimal m_Price = 11.5M;
public override decimal GetPrice() { return m_Price; }
}
public class Car : Travel
{
private decimal m_Price = 16.5M;
public override decimal GetPrice() { return m_Price; }
}
// you can use factory using this code
...
Console.WriteLine( Travel.TravelFactory(Travel.Types.Air).GetPrice().ToString() );
...