抽象的
当设计需要像 [GoF] 所述的“抽象工厂模式”(包括多个产品和某些产品系列)时,设置 IoC 可能会变得有点棘手。特别是当具体的工厂实现需要通过运行时参数调度并在一些后续组件之间共享时。
鉴于以下 API,我试图设置我的 IoC(在本例中为 Ninject)以检索Configuration
通过IConfigurationFactory
. 配置存储一个IFactory
实例,其实现由 type 的运行时参数确定ProductFamily
。之后,工厂在配置中创建的产品类型应始终与请求的匹配ProductFamily
。由类组成的子图Component
具有相同的IFactory
per Configuration
。
public enum ProductFamily { A, B }
public interface IProduct1 { }
public interface IProduct2 { }
public interface IFactory
{
IProduct1 CreateProduct1();
IProduct2 CreateProduct2();
}
public class Configuration
{
public readonly IFactory factory;
public readonly Component component;
public Configuration(IFactory factory, Component component)
{
this.factory = factory;
this.component = component;
}
}
public class Component
{
public IFactory factory;
public Component(IFactory factory) { this.factory = factory; }
}
public interface IConfigurationFactory
{
Configuration CreateConfiguration(ProductFamily family);
}
测试
为了澄清预期的行为,我在 vstest 中添加了我的测试代码。但是提前添加了一些内容,感谢@BatterBackupUnit 询问这些细节:
- 工厂只需要
ProductFamily
作为参数在实现之间进行选择,没有别的 - 每个
Configuration
及其后续对象(如Component
, )共享同一个工厂实例
所以我希望这会有所帮助:)
[TestMethod]
public void TestMethod1()
{
var configFac = ComposeConfigurationFactory();
// create runtime dependent configs
var configA = configFac.CreateConfiguration(ProductFamily.A);
var configB = configFac.CreateConfiguration(ProductFamily.B);
// check the configuration of the factories
Assert.IsInstanceOfType(configA.factory.CreateProduct1(), typeof(Product1A));
Assert.IsInstanceOfType(configB.factory.CreateProduct1(), typeof(Product1B));
Assert.IsInstanceOfType(configA.factory.CreateProduct2(), typeof(Product2A));
Assert.IsInstanceOfType(configB.factory.CreateProduct2(), typeof(Product2B));
// all possible children of the configuration should share the same factory
Assert.IsTrue(configA.factory == configA.component.factory);
// different configurations should never share the same factory
var configA2 = configFac.CreateConfiguration(ProductFamily.A);
Assert.IsTrue(configA.factory != configA2.factory);
}
这个问题已经解决了,因此我删除了所有不必要的绒毛。
感谢@BatteryBackupUnit 您的时间和精力最好的问候
伊萨亚斯