如何在泛型中使用工厂模式

本文关键字:工厂 模式 泛型 | 更新日期: 2023-09-27 17:54:45

我希望创建一个PresenterFactory,它显然负责创建演示器实例。

根据本题提供的代码示例:

如何Moq这个视图?

和@Pacane的回答,我想我会这样写:

PresenterFactoryTests

[TestClass]
public class PresenterFactoryTests {
    [TestClass]
    public class Instance : PresenterFactoryTests {
        [TestMethod]
        public void ReturnsInstantialized() {                
            // arrange
            Type expected = typeof(PresenterFactory);
            // act
            PresenterFactory actual = PresenterFactory.Instance;
            // assert
            Assert.IsNotNull(actual);
            Assert.IsInstanceOfType(actual, expected);
        }
        [TestMethod]
        public void ReturnsSame() {
            // arrange
            PresenterFactory expected = PresenterFactory.Instance;
            // act
            PresenterFactory actual = PresenterFactory.Instance;
            // assert
            Assert.AreSame(expected, actual);
        }
    }
    [TestClass]
    public class Create : PresenterFactoryTests {
        [TestMethod]
        public void ReturnsAuthenticationPresenter { 
            // arrange
            Type expected = typeof(IAuthenticationPresenter);
            // act
            IAuthenticationPresenter actual = 
                PresenterFactory
                    .Instance
                    .Create<IAuthenticationPresenter, IAuthenticationView>(
                        new MembershipService());
           // assert
           Assert.IsInstanceOfType(actual, expected);
        }
        // Other tests here...
    }
}

PresenterFactory

public sealed PresenterFactory {
    private PresenterFactory() { }
    public static PresenterFactory Instance { get { return getInstance(); } }
    P Create<P, V>(params object[] args) where P : IPresenter<V> where V : IView { 
        V view = (V)Activator.CreateInstance<V>();
        return Activator.CreateInstance(typeof(P), view, args);
    }
    private static PresenterFactory getInstance() {
        if (instance == null) instance = new PresenterFactory();
        return instance;
    }
    private static PersenterFactory instance;
}

ApplicationPresenter

public class ApplicationPresenter : Presenter<IApplicationView>, IApplicationPresenter {
    public ApplicationPresenter(IApplicationView view, PresenterFactory presenters)
        : base (view) {
        Presenters = presenters;
        // other initializing stuff here...
    }      
}

然而,由于类型的限制,我似乎无法做到上述测试中所述的。

在我的PresenterFactoryTests.Create.ReturnsAuthenticationPresenter测试方法中,当我使用接口作为类型参数时,它在运行时编译并抛出,因为Activator.CreateInstance不能创建接口的实例。

除此之外,如果我输入具体类型,它会抱怨它不能显式地将类型转换为我的类型约束,尽管两者都实现了给定的接口。

PresenterFactoryApplicationPresenter所需要的,我将通过它的构造函数注入它,以便应用程序可以实例化所有可用的呈现者,这取决于用户所要求的特性。

我错过了什么?

如何在泛型中使用工厂模式

我认为你需要一个更通用的参数-具体类型的视图,因为你需要两个具体的类型(视图和演示器能够创建它们)和视图的接口类型:

P Create<P, V, IV>(params object[] args) 
      where P : IPresenter<V> where V :IV, IV: IView {