简体   繁体   English

工厂模式,返回一个通用类并有一个参数

[英]Factory pattern, return a generic class and have an argument

I have this implementation of Factory Pattern 我有这个工厂模式的实现

public interface IFactory<T>
{
    T GetObject();
}

public class Factory<T> : IFactory<T> where T : new()
{
    public T GetObject()
    {
        return new T();
    }
}

But I'd like than GetObject return an instance of a generic class Repository<Customer> ( Repository implement IRepository ) and the factory has an argument (ISession type) 但是我想比GetObject返回通用类Repository<Customer>Repository implement IRepository )的实例,并且工厂有一个参数(ISession类型)

The result should be : 结果应为:

IRepository<ICustomer> myRepo = new Factory<ICustomer>(session);

How can I do this ? 我怎样才能做到这一点 ?

Thanks, 谢谢,

Consider having a parameterless constructor instead, and some initialization function that takes the parameter. 考虑改用无参数构造函数,以及一些带有参数的初始化函数。 Other than not being able to pass a parameter through your factory, consider the case when you will want to deserialize your objects. 除了无法通过工厂传递参数外,请考虑要反序列化对象的情况。 They should be constructed and then the parameters should be filled one by one after that. 应该先构造它们,然后再逐个填充参数。

Does it have to be so generic? 它必须是如此通用吗? Why not like this? 为什么不这样呢?

public interface IFactory<T>
{
    IRepository<T> Create(ISession session);
}

public class RepositoryFactory<T> : IFactory<T> where T : new()
{
    public IRepository<T> Create(ISession session)
    {
        return new IRepository<T>();
    }
}

I'm not sure if you really need that level of generic but you can use generic fluent factory approach and have initialization function not from constructor instead. 我不确定您是否真的需要通用级别,但是可以使用通用流利的工厂方法,而不必使用构造函数提供的初始化功能。

  var CustomerGeneric = GenericFluentFactory<Customer, WebSession>
                        .Init(new Customer(), new WebSession())
                        .Create();


public static class GenericFluentFactory<T, U>
{
    public static IGenericFactory<T, U> Init(T entity, U session)
    {
        return new GenericFactory<T, U>(entity, session);
    }        
}

public class GenericFactory<T, U> : IGenericFactory<T, U>
{
    T entity;
    U session;

    public GenericFactory(T entity, U session)
    {
        this.entity = entity;
        this.session = session;
    }

    public T Create()
    {
        return this.entity;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM