We often use things we do not even think about because it's like this.
I do not like to place mechanism pendants on an object that is domain specific.
If I have a screen control or a client that has some action that triggers an event my normal is to use some form of event where the object has a list of subscribers that obviously grows as it is taking interested objects (observers) in any change of state or behavior that this observed object is willing to warn that has occurred, is occurring or will occur. The control mechanism stays on this object and has the cost in it.
I wondered if it was not more interesting to have a separate observation object, then this object that was observed tells the observation object that it has available events and the observing objects sign those desired events. All this object is responsible for the mechanism of observation and the objects that communicate do not have their own mechanisms reducing their responsibility, apparently improving the cohesion and coupling.
I am mainly concerned with the object load state that is not part of the domain of it. I know it's priceless in many cases and I should not worry too much about it. But the question remains whether from the strict engineering point of view it makes sense to do something like this.
I do not want to know which one is the best, but if I'm looking at the overall picture properly or missed something important.
Illustrative example only simplified and naively in pseudocode:
class Score
value = 0
Increase() {
value++
Changed(this)
}
Score() {
RegisterEvent(this, Increase)
}
~Score() {
UnregisterEvent(this, Increase)
}
class Observation {
observables[] = new[]
RegisterEvent(obj, method) {
observables[obj << ptrLength + method] = new[]
}
UnregisterEvent(obj, method) {
observables[obj << ptrLength + method] = null
}
SubscribeEvent(obj, method, action) {
observables[obj << ptrLength + method] += action
UnsubscribeEvent(obj, method, action) {
observables[obj << ptrLength + method] -= action
}
}
class App {
static player1 = new Score()
static player2 = new Score()
}
class Screen {
Screen() {
SubscribeEvent(player1, Score.Increase, PaintScore1) {
SubscribeEvent(player2, Score.Increase, PaintScore2) {
}
~Screen() {
UnsubscribeEvent(player1, Score.Increase, PaintScore1) {
UnsubscribeEvent(player2, Score.Increase, PaintScore2) {
}
PaintScore1(obj) { ... }
PaintScore2(obj) { ... }
}
class Fire {
...
Reached(player) {
(player == 1 ? player1 : player2).Increase()
}
}
Would this be the same as the Mediator standard? If so, would Mediator be a replacement for the Observer? Or they serve different purposes. With the advent of Mediator would the Observer be obsolete? Or do they complement each other? Or would it be wrong for them to complement each other?
Would this be the Event Aggregator? And is this just one of the many things I thought I invented? Dammit Fowler! : P