Home  /  Questions  /  Question



50   50
Sep 13, 2013


Is the Factory Pattern correct for my message system?

Hi, 

Just started to read the amazing books in the Design Pattern Framework 4.5. However, I am a bit confused.

Say I have a messaging system which can send each message using different channel.
Is it a mistake to define Factory class -> Create function based on Enum which due to value return the right channel?
Since the creation is dynamic at run-time as I understand a Factory pattern doesn't match here...

Any suggestions?

Here is some code: 
public class Channel
{
  public abstract void SendMessage();
}


public class EmailChannel : Channel
{
   public void SendMessage()
   {

   }
}


public class SmsChannel : Channel
{
   public void SendMessage()
   {

   }
}



public class MessageSenderfactory
{
    public static Channel CreateChannel(ChannelType ct)
    {
       switch(ct)
       {
         case Sms: 
            return new ChannelSms();
         case Email:
            return new EmailChannel();
       }
    }
}


public Enum ChannelType
{
  Sms = 1,
  Email
}

 



508   99.9
Sep 13, 2013
Hello Amit: 

This seems like a fine implementation of the Factory Method design pattern.
It allows each message channel to implement its own SendMessage implementation.
Furthermore, you can easily add a third message channel with little effort. 

Hope this helps.
Jack

 3 comments
 
Thanks Jack, I wasn't sure since i understood from samples thats this implementation is "less favorite" , Now i understand that there are time you don't have a choice .. Amit. --- Amit Malina  Sep 13, 2013
 
Btw .. is it reasonable to mix say ... Builder and Factory ? --- Amit Malina  Sep 13, 2013
 
Yes, you can combine any pattern with any other pattern if it makes sense for your situation. Just a heads up, the Builder pattern is used rather infrequently so be sure that the pattern is truly beneficial to your scenario. . --- Jack Poorte  Sep 13, 2013