我正在尝试实现一个工厂。据我了解,以下简单代码是工厂(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();
}
}
遗憾的是,我被困在一个带有 VS2005 的 .NET 2.0 项目上,因此不能使用“var”关键字。谁能给我任何关于如何完成或如何在 .NET 2.0 中完成的建议。
所以,一个更现实的例子:
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");
}
}
}
我的抽象基类
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
}
还有我的 2 个继承类
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";
}
}