mardi 12 mai 2015

How to pass params into a Factory for object creation?

I have RecipientTypesFactory that is going to create objects of the type RecipientType. For RecipientTypes object I have the followin hierarchy:

public interface RecipientType{
    public abstract Object accept(RecipientTypeVisitor v);
}

public class DynamicGroupType implemetns RecipientType{

    private Integer dynamicGroupId;

    public Object accept(RecipientTypeVisitor visitor){
        return visitor.visit(this);
    }
    //GET, SET
}

public class StaticGroupType implements RecipientType{

    private Integer staticGroupId;

    public Object accept(RecipientTypeVisitor visitor){
        return visitor.visit(this);
    }
    //GET, SET
}

RecipientTypesFactory itself looks as follows:

public enum RecipientTypeEnum {
    STATIC_GROUP, DYNAMIC_GROUP
}

public class RecipientTypesFactory{
    private Map<RecipientTypeEnum, RecipientTypeCreator> creators;

    public RecipientType createRecipientType(RecipientTypeEnum t){
        return creators.get(t).create();
    }
}

I'm not going to provide the actual definition of RecipientTypeCreator and its hierarchy because I don't think it's very important.

Now I have the controller:

public class CreateMailingController{
    private RecipientTypesFactory recipientTypesFactory;
    private Integer dynamicGroupId;
    private Integer staticGroupId;
    private RecipientTypeEnum selectedType;

    //GET, SET, other staff

    public void createMailing(){
        Type t = recipientTypesFactory.createRecipientType(selectedType);
        //How to initialize t's field with an appropriate value?
    }
}

The thing is RecipientTypesFactory and its creators know nothing about CreateMailingController's dynamicGroupId and staticGroupId values. Those values are setting up by some user from web-interface. Therefore the factory cannot initialize the corresponding field of a type to create with these values.

RecipientTypesFactory and its creators are spring beans.

Question: How can I pass the values of dynamicGroupId and staticGroupId to the Factory in a flexible way and avoid wiriting switch-case like code? Is that possible?

Maybe there's another patter for that purposes. In fact the factory is creating the prototype of an object.

Aucun commentaire:

Enregistrer un commentaire