If two children have the same parent, how does an event firing from one child get handled by the second child.
So the example is:
TrackerContainer is the parent of Tracker and TrackerPanel. TrackerPanel is the parent of PlayButton. Tracker is a timer-like class and has a stop() method. PlayButton has an activate() and deactivate() method.
How does a call to the stop() method from within Tracker call the deactivate() method from within PlayButton(). I thought of having the time keeping track of occurring in the TrackerContainer class, but that doesn't feel right.
EDIT Here it is in code (JavaScript, by the way):
function TrackerContainer
{
this.display = new Tracker();
this.panel = new TrackerPanel();
}
function Tracker
{
this.play = function() { /* yada */ }
this.stop = function() { /* yada */开发者_开发知识库 }
}
function TrackerPanel
{
this.playButton = new PlayButton();
}
function PlayButton
{
this.activate = function() { /* method called when Tracker is playing */ }
this.deactivate = function() { /* method called when Tracker is stopped */ }
}
You didn't indicate the language, so we'll talk in general terms. This is the Model-View-Controller pattern. Your PlayButton is a view. Your Tracker is the model and the TrackerContainer is the controller (I'm guessing; it might be a view, in which case you should have a separate controller object).
The view's job is to display things. The model's job is keep track of data. The controller coordinates between the two.
For this problem, you probably want an Observer pattern. The controller observes the model and updates the view as needed. One way to implement the Observer pattern is with a delegate or listener. You create an interface called TrackerListener
that TrackerContainer
conforms to, with methods like trackerDidStart()
and trackerDidStop()
. Tracker
HAS-A TrackerListener
and calls the listener methods whenever the state changes. TrackerContainer
then updates the button's state.
The simplest solution would be to pass the Tracker a instance of the PlayButton. The tracker, in stop()
would call playbutton.deactivate()
. If it makes you feel more oop-complient, you could make PlayButton implement a Deactivatible interface, which the tracker would work with.
精彩评论