What should I do if i have a factory method which requires different parameters for different implem

Posted by Sam Holder on Stack Overflow See other posts from Stack Overflow or by Sam Holder
Published on 2010-04-02T16:02:25Z Indexed on 2010/04/02 16:13 UTC
Read the original article Hit count: 264

Filed under:
|
|
|

I have an interface, IMessage and a class which have several methods for creating different types of message like so:

class MessageService
{
    IMessage TypeAMessage(param 1, param 2)
    IMessage TypeBMessage(param 1, param 2, param 3, param 4)
    IMessage TypeCMessage(param 1, param 2, param 3)
    IMessage TypeDMessage(param 1)    
}

I don't want this class to do all the work for creating these messages so it simply delegates to a MessageCreatorFactory which produces an IMessageCreator depending on the type given (an enumeration based on the type of the message TypeA, TypeB, TypeC etc)

interface IMessageCreator
{
     IMessage Create(MessageParams params);
}

So I have 4 implementations of IMessageCreator: TypeAMessageCreator, TypeBMessageCreator, TypeCMessageCreator, TypeDMessageCreator

I ok with this except for the fact that because each type requires different parameters I have had to create a MessageParams object which contains 4 properties for the 4 different params, but only some of them are used in each IMessageCreator.

Is there an alternative to this? One other thought I had was to have a param array as the parameter in the Create emthod, but this seems even worse as you don't have any idea what the params are. Or to create several overloads of Create in the interface and have some of them throw an exception if they are not suitable for that particular implementation (ie you called a method which needs more params, so you should have called one of the other overloads.)

Does this seem ok? Is there a better solution?

© Stack Overflow or respective owner

Related posts about factory-method

Related posts about parameters