因此,我了解 IoC,尤其是在“将未知的混凝土注入”到课程中时。在构造函数中或通过属性将“ILogger”注入类的最通用示例。
现在,我有一个较旧的工厂模式,我试图弄清楚如何/是否可以转换为 IoC。(我正在使用 Unity,仅供参考)。
下面我有我的旧工厂模式。它基本上是根据当前的天然气(石油)价格做出工厂决定。如果汽油真的很贵,我会骑自行车。如果汽油价格中等,我会开车。如果汽油变得便宜,那我开卡车上班!(这是一个愚蠢的例子,请随它去吧)。
我不明白的是我如何将其“翻译”为 IoC ......当涉及到返回哪个具体类的业务逻辑决策时。
我错过了什么?也许我还需要工厂?还是我错过了一些关键概念?
在此先感谢您的帮助...
namespace MyApp
{
public interface IVehicle
{
void MakeTrip();
}
public class Bicycle : IVehicle
{
public void MakeTrip() { Console.WriteLine("Bicycles are good when gas is expensive."); }
}
public class Car : IVehicle
{
public void MakeTrip() { Console.WriteLine("Cars are good when gas is medium priced"); }
}
public class PickupTruck : IVehicle
{
public void MakeTrip() { Console.WriteLine("Gas is back to 1980's prices. Drive the truck!"); }
}
public static class VehicleFactory
{
public static IVehicle GetAConcreteVehicle(decimal priceOfGasPerGallon)
{
if (priceOfGasPerGallon > 4.00M)
{
return new Bicycle();
}
if (priceOfGasPerGallon > 2.00M)
{
return new Car();
}
return new PickupTruck();
}
}
public class TripControllerOldFactoryVersion
{
public decimal PriceOfGasPerGallon { get; set; }
public TripControllerOldFactoryVersion(decimal priceOfGas)
{
this.PriceOfGasPerGallon = priceOfGas;
}
public void TakeATrip()
{
IVehicle v = VehicleFactory.GetAConcreteVehicle(this.PriceOfGasPerGallon);
v.MakeTrip();
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
TripControllerOldFactoryVersion controller1 = new TripControllerOldFactoryVersion(5.00M);
controller1.TakeATrip();
TripControllerOldFactoryVersion controller2 = new TripControllerOldFactoryVersion(3.33M);
controller2.TakeATrip();
TripControllerOldFactoryVersion controller3 = new TripControllerOldFactoryVersion(0.99M);
controller3.TakeATrip();
}
catch (Exception ex)
{
Exception exc = ex;
while (null != exc)
{
Console.WriteLine(exc.Message);
exc = exc.InnerException;
}
}
finally
{
Console.WriteLine("Press ENTER to Exit");
Console.ReadLine();
}
}
}
所以上面是工厂版本。
因此,我试图找出将其转换为 IoC 的最佳方法,但仍有一些“基于天然气价格”的逻辑来确定 IVehicle。
启动代码如下。
public class TripControllerIoCVersion
{
public IVehicle TheVehicle { get; set; }
public TripControllerIoCVersion(IVehicle v)
{
this.TheVehicle = v;
}
public void TakeATrip()
{
if (null != this.TheVehicle)
{
this.TheVehicle.MakeTrip();
}
}
}