I find myself writing something like an event driven frame work, and I was pondering the various ways in which I've seen it done. It seemed to me, that the two main ways are "callbacks" and "interfaces".
Callbacks, of course, are obvious in what they do and how they work, and it's how most GUI Toolkits, such as tk, do things. You call some function and pass a coderef to it. Example:
sub called
{
print "You pressed a button!";
}
my $button = new Button( name=>'foo', callback=>\&called );
The coderef passed to the constructor is derefenced when ever it's need to, and the call back is called.
The second way, which I've called "interface", although perhaps "inheritance" or some other word would better describe it, is how, for example, WxWindows does things. In this case, you don't call a function and pass a coderef to it, you simply implement a specific "interface" in your base class and then the other code uses this interface to interact with you. If that wasn't particularly clear, perhaps this example will help:
class MyButton;
use Base 'Button';
sub on_click
{
print "You pressed a button";
}
package main;
my $button = new MyButton();
In this case you inherit the "other" methods, constructor, destructor, etc from a base class, then just implement the interface you wish to provide.
The pros and cons, as far as I can tell, is mostly that callbacks allow you to pass annonymous subs, or the same subref to multiple callbacks, but both of those are fairly minor pros, so this is what I ask you: Are there any other pros/cons I missed? Which do you prefer using? Why?