i have a message object that i can add content to. The message can also be sent. Is it better to provide a "deep module" that hides the dispatcher from the client, or is it better to have only one responsibility per class?
Example: expose the dispatcher
class Message {
void add(String key, String value) { ... }
}
class Dispatcher {
Result send(Message message) { ... }
}
class DispatcherFactory {
Dispatcher create() { return new DefaultDispatcher(); }
}
Example: Hide the dispatcher
class MessageFactory {
Message create() { return new Message(DefaultDispatcher()); }
}
class Message {
Message(Dispatcher dispatcher) { ... }
void add(String key, String value) { ... }
Result send() {
return dispatcher.dispatch(content);
}
}
In my opinion the latter is easier to use and also testable, but violates the SRP. Which one is better?
In my opinion the latter is easier to use and also testable, but violates the SRP
it does not violate SRP as implementation of Dispatcher
class is located in Dispatcher
class. If Message
class would have implentation of Dispatcher
class, then it will be violtion of SRP class.
Which one is better?
In my view, the second implementation is better if you can slightly modify your implementation of MessageFactory Mediator pattern.
Let me show an example:
class MessageFactory {
Message create(DefaultDispatcher defaultDispatcher)
{ return new Message(defaultDispatcher); }
}
If you want to have relationship publisher and subscriber. I mean publisher send messages to subscribers, then you can use Observer
pattern.
As wiki says about Observer pattern:
The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.