1. Customize by delegation instead of subclassing
1.1 A part of every RubyObjC application
Nearly every RubyObjC application contains some variant of the code below:
# The application delegate configures the application # after all basic services have been started class ApplicationDelegate < ObjC::NSObject imethod "applicationDidFinishLaunching:" do |sender| # application setup... end end # keep a reference to the delegate to keep it safe # from Ruby garbage collection $delegate = ApplicationDelegate.alloc.init ObjC::NSApplication.sharedApplication.setDelegate_($delegate)
The purpose of this is to cause the application to do something special once it has finished setting up its internal structures. In many frameworks, this would be done by subclassing the application class (in this case, it is NSApplication). But NeXTStep introduced another idea, that of delegation. Instead of modifying the class itself, we create a new object with the desired behavior and provide this delegate to the object we wish to modify. This has two advantages: we can change behaviors on an instance-by-instance basis, and we can avoid adding too many layers to our program’s class hierarchy.
Did you find an error? Is something missing? Post your comment or suggestion below!
Comments (0) post