Is the Observer pattern adequate for this kind of scenario?
- by Omega
I'm creating a simple game development framework with Ruby.
There is a node system. A node is a game entity, and it has position. It can have children nodes (and one parent node). Children are always drawn relatively to their parent.
Nodes have a @position field. Anyone can modify it. When such position is modified, the node must update its children accordingly to properly draw them relatively to it.
@position contains a Point instance (a class with x and y properties, plus some other useful methods).
I need to know when a node's @position's state changes, so I can tell the node to update its children.
This is easy if the programmer does something like this:
@node.position = Point.new(300,300)
Because it is equivalent to calling this:
# Code in the Node class
def position=(newValue)
@position = newValue
update_my_children # <--- I know that the position changed
end
But, I'm lost when this happens:
@node.position.x = 300
The only one that knows that the position changed is the Point instance stored in the @position property of the node. But I need the node to be notified!
It was at this point that I considered the Observer pattern. Basically, Point is now observable.
When a node's position property is given a new Point instance (through the assignment operator), it will stop observing the previous Point it had (if any), and start observing the new one. When a Point instance gets a state change, all observers (the node owning it) will be notified, so now my node can update its children when the position changes.
A problem is when this happens:
@someNode.position = @anotherNode.position
This means that two nodes are observing the same point. If I change one of the node's position, the other would change as well. To fix this, when a position is assigned, I plan to create a new Point instance, copy the passed argument's x and y, and store my newly created point instead of storing the passed one.
Another problem I fear is this:
somePoint = @node.position
somePoint.x = 500
This would, technically, modify @node's position. I'm not sure if anyone would be expecting that behavior. I'm under the impression that people see Point as some kind of primitive rather than an actual object.
Is this approach even reasonable? Reasons I'm feeling skeptical:
I've heard that the Observer pattern should be used with, well, many observers. Technically, in this scenario there is only one observer at a time.
When assigning a node's position as another's (@someNode.position = @anotherNode.position), where I create a whole new instance rather than storing the passed point, it feels hackish, or even inefficient.