How to connect a Morph to an Object that it is supposed to visualize in Morphic?

470 views Asked by At

Let's say i have Bird class and BirdMorph class. Birds have a position, and i want BirdMorphs to change their position on the screen, whenever the corresponding bird changes it's position.

What is the intended way to connect a Morph to the Object it is supposed to visualize in Morphic?

2

There are 2 answers

1
codefrau On BEST ANSWER

Typically a BirdMorph would hold a Bird in an instance variable, and update its own position in its step method.

Think of it this way: Every object needs to be "held" somewhere. If there is no reference to it, it gets garbage-collected automatically. In Morphic, that reference is normally rooted in the World, every morph is referenced via its container's submorphs collection.

So it makes sense then that your morph holds onto the "domain model". E.g. you might have an object BirdSimulation which holds all the Birds, and a window on screen holding onto the BirdSimulation. Then when you close the window, the simulation objects will be gone, too.

If your program is mainly visual you might not even need a separate Bird class. Instead, the morph could just be "a bird". That can simplify the design considerably.

0
ARA On

IMHO your first thought was right : MVC is the way to go. Holding a reference from the BirdMorph to its Bird model seems to be the simplest way to do this, but With the Observer pattern your BirdMorph is an "observer" of your Bird : the BirdMorph registers itself to the Bird when created to be notified for each event. Whenever the Bird moves it notifies all its observers of his move. So you can have multiple observers for a Bird, for example one Morph for display (position and others), one for logging (to a network peer for exmaple), etc ... Less "hard" references in code, less spagethi.

Lot of frameworks are built upon this pattern because it breaks dependencies between objects and simplifies a lot.


Plus there is a package for that in Pharo Announcements: an Object Dependency Framework