I’m planning an application in C# which has a feature of sending messages.
ATM I’m doing the non-businesslogics and frameworking stuff.
The idea was to make an abstract base class which is inherited when used.
In there, i’ll implement what should happen with the message and when another one should be sent
Ex:
abstract class BaseMessage
{
public abstract void OnNewMessage(Message message);
public void Send(Message message)
{
//Sending, i.E. HTTP, RabbitMQ, whatever
}
}
class MessageUse1 : BaseMessage
{
public override void OnNewMessage(Message message)
{
//.. Do whatever
}
public void ShoudSendMessage(Message message)
{
Send(new Message());
}
}
But:
What if I – for whatever reason – want to change the way messages are sent? I don’t want to change each implementation.
How would i structure this?
Ideas:
-
Making an Interface for ALL methods and only implement the Send in the base class. I could then change my baseclass implementation BUT i would have to change it in the derived class too.
-
Interface with OnNewMessage() –> Implement it in the client and give an instance of the class to a factory, which returns me the concrete implementation. But i could not do the Send in this way.
I’d love to hear a solution but i’m also glad if you can tell me, what i should search for.
Thanks a lot!
0
I believe that the Template Method Pattern is the correct way of modeling your problem. Using the pattern, you would implement the common behavior/algorithm in the base class and, the things that are different for each message, in the concrete classes. Also, you should use an interface containing all the public methods, which is implemented by the base class. This way, if you have multiple algorithms implementation, you can have distinct “families” of templates, and your client code will be independent of it.