would this still count as the factory pattern if I would use, instead of a parameter, use single methods.
For example instead of this
public class Mapper开发者_StackOverflow中文版Factory { // will be made as an instance
public Mapper<?> typeMapper(String type)
{
switch(type){
case "option1": return new MapperType1();
case "option2": return new MapperType2();
case "option3": return new MapperType3();
}
}
}
create a class like this so you just need to choose 'MapperFactory.option1();' instead of using 'MapperFactory.typeMapper("option1");
public class MapperFactory { // will be made as an instance
public Mapper<?> option1(){return new MapperType1();}
public Mapper<?> option2(){return new MapperType2();}
public Mapper<?> option3(){return new MapperType3();}
}
Greets
I don't know if there's a hard-and-fast rule here, but in my opinion, your second example is not a factory pattern. I think a factory pattern needs to allow for some sort of dynamic behavior in the implementation. In other words, the method must require input (even if the factory method takes no formal parameters, it must obtain some input to affect the implementation, be it via fields of the enclosing class, or some static data obtained elsewhere) and it must allow for the possibility of returning different types based on that input. I think your second example is simply a series of methods that instantiate a precise class and returns it.
So now I ask, why are you exploring a factory pattern in the first place? If, at compile time, you always want to instantiate the same class (i.e. MapperFactory.option1()
) why don't you just use the new operator in the first place? In your second example, your "factory" methods provide absolutely no advantage over the stock new operator.
If you need to use this in a strategy pattern in any way i would suggest an enum:
public enum Mapper{
option1{
public Mapper<?> getInstance(){
return new MapperType1();
}
},
option2{
public Mapper<?> getInstance(){
return new MapperType2();
}
},
option3{
public Mapper<?> getInstance(){
return new MapperType3();
}
};
public abstract Mapper<?> getInstance();
}
this way you can construct functions like:
public void foo(Mapper mapper){
Mapper<?> map = mapper.getInstance();
}
which is great if you are planning on adding extra mappers
精彩评论