samedi 29 avril 2017

Factory CreateInstance arguments not neessary for a specific subtype

I have a factory class and one create instance method

CreateInstance(EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita, IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider)

the factory can instantiate two differents sub-types depending on the value of tipoParametroEntita.TipoCampo.IdTipoCampo

The point is the second argument of CreateInstance (parametroEntitaMultiValoreDataSourceProvider) is used only for creating instance of TipoEntitaTipoParametroEntitaMultiValore
whereas is not used in creating instance of TipoEntitaTipoParametroEntitaSingoloValore

public class TipoEntitaTipoParametroEntitaFactory : ITipoEntitaTipoParametroEntitaFactory
        {
            /// <summary>
            /// Creates an instance of TipoEntitaTipoParametroEntitaSingoloValore or  TipoEntitaTipoParametroEntitaMultiValore 
            /// </summary>
            public TipoEntitaTipoParametroEntita CreateInstance(EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita, IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider)
            {
                if (tipoParametroEntita.TipoCampo.IdTipoCampo == (int)EntityModel.Enum.TipoCampo.CampoLibero ||
                    tipoParametroEntita.TipoCampo.IdTipoCampo == (int)EntityModel.Enum.TipoCampo.CampoLiberoMultiLinea)
                {
                    return new TipoEntitaTipoParametroEntitaSingoloValore(tipoParametroEntita);
                }

                if (tipoParametroEntita.TipoCampo.IdTipoCampo ==
                    (int)EntityModel.Enum.TipoCampo.DropdownListQueryDataSource ||
                    tipoParametroEntita.TipoCampo.IdTipoCampo ==
                    (int)EntityModel.Enum.TipoCampo.DropdownListTableDataSource)
                {
                    return new TipoEntitaTipoParametroEntitaMultiValore(tipoParametroEntita,
                        parametroEntitaMultiValoreDataSourceProvider);
                }

                return null;

            }
        }

Im doubtful about this adopted pattern as I always need to pass an instance of IParametroEntitaMultiValoreDataSourceProvider even if it could not be necessary and moreover someone reading the signature of the method might be led to think that for creating any type of TipoEntitaTipoParametroEntita an instance of IParametroEntitaMultiValoreDataSourceProvider is required.

What could be a better approach? Two distinct factories? Only one factory and two CreateInstance (one returning TipoEntitaTipoParametroEntitaSingoloValore and the other TipoEntitaTipoParametroEntitaMultiValore)?

I both of the cases I should already know which factory or which CreateInstance to call so I should check tipoParametroEntita.TipoCampo.IdTipoCampo every time in advance. But I'd like to keep this logic only in one place.

Aucun commentaire:

Enregistrer un commentaire