I am trying to implement a factory. As I understand it, the following simple code is a factory (C#)
private void methodName()
{
var result = GetTypeByName("nameOfType")
}
private AbstractClassName GetTypeByName(string nameOfType)
{
switch(nameOfType)
{
case "type1":
return new inheritedFromAbstractClass();
case "type2":
return new alsoInheritedFromAbstractClass();
default:
throw new Exception();
}
}
I am sadly stuck on a .NET 2.0 project with VS2005 and as such can't use the 'var' keyword. Can any one give me any advice on how something like this was done or how it can be done in .NET 2.0.
So, a more real life example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting order");
Console.WriteLine("Press 1 or 2");
string s = Console.ReadLine();
var order = GetOrderByIdFromFactory(s);
order.ShippingAddress = "My House, England";
Console.WriteLine(order.Ship());
Console.ReadKey();
}
private static OrderShipment GetOrderByIdFromFactory(string s)
{
OrderShipment os = default(OrderShipment);
switch (s)
{
case "1":
return new FedExShipping();
break;
case"2":
return new UpsShipping();
break;
default:
throw new NotImplementedException("Not implemented");
}
}
}
My Abstract base class
public abstract class OrderShipment
{
#region Properties
public string ShippingAddress { get; set; }
internal string Label { get; set; }
private readonly TextWriter _text = new StringWriter();
#endregion
#region Public Methods
internal string Ship ()
{
VerifyShippingData();
GetShippingLabelFromCarrier();
PrintLabel();
return _text.ToString();
}
internal virtual void VerifyShippingData()
{
if (string.IsNullOrEmpty(ShippingAddress))
{
throw new ApplicationException("Invalid Address");
}
}
internal abstract void GetShippingLabelFromCarrier();
internal virtual void PrintLabel()
{
_text.Write(Label);
}
#endregion
}
And my 2 inheriting classes
public class FedExShipping : OrderShipment
{
internal override void GetShippingLabelFromCarrier()
{
//ToDo perform logic
Label = "FedEx Label Details";
}
}
public class UpsShipping : OrderShipment
{
internal override void GetShippingLabelFromCarrier()
{
//ToDo logic
Label = "Ups Label Details";
}
}
Why not somethign like this:
AbstractClassName result = GetTypeByName("nameOfType")
var
keyword is not an innovation, it's just let's you do not type AbstractClassName
(in this concrete example). So within this concrete question scenario you don't loose much using 2.0