Question

Is it ok to implement factory and get the type in the constructor, so .CreateInstace() will be parameter-less or this will be antipattern and I should do my best to avoid it?

I assume that during system runtime only one predefined type should be instantiated by the factory

Was it helpful?

Solution

I assume that during system runtime only one predefined type should be instantiated by the factory

Not necessarily as this will force you to create a factory class for each concrete type you wish to create.

Constructor injection (i.e. providing the type via the constructor) is usually preferred over Method injection (i.e. providing the type via a parameter in a method call), but as I said what if the factory needs to create more than one type based on the parameters passed to it at run-time, then it would be more convenient to pass those parameters to the createInstance() method rather than creating a new factory per type.

Bottom line, I usually prefer to pass the parameters to the createInstance() method, and give the factory any things it need to do its job via the constructor.

OTHER TIPS

For me, No. That is because later on your factory cannot be flexible enough or being hard during dependency injected, as such:

public class Factory{
    public Factory(Type t, IocContainer con){
       // param assignments
    }
    public IClass GetInstance(){
        return con.Resolve<t>();
    }
}

Will get you confused about what is that being injected (2 of them are unrelated each other. One is type? And other is IocContainer? It also makes your Factory has states. Moreover, how if I inject type of interface? Can your factory create a class from interface?

Rather, why don't you just accept the class itself?

public class Factory{
    public Factory(IClass cls){
       // param assignments
    }
    public IClass GetInstance(){
        return cls;
    }
}

This is more self-documented and crystal clear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top