Express Abstractionism
July 4, 2008 11:19 AM
The last few posts have gone into detail on some techniques to reduce the coupling between different parts of the CocoaBugs framework. Specifically, we want to move towards a plugin-based solution for running different ALife models.
Plists and key-value observation are the main tool we've used so far. We've managed to greatly reduce the amount of knowledge our app controller needs to have about the ALife models to provide statistics and configuration services.
However, there is still one huge amount of "knowledge" our AppController has about the models it's running, and is the most significant barrier our framework needs to surmount. See if you can spot it:
AppController.m:
ControllerOfLife *lifeController = [[ControllerOfLife alloc] init];
Eep! That is just no good at all.
The first thing we can do is define an Objective-C protocol for the interface of an ALife controller. That way, we can be sure that the app controller can talk to the ALife controllers, without needing to be compiled alongside them or have knowledge about their implementation.
For now, we'll just include a few methods that most every ALife model will probably implement.
@protocol ALifeController <NSObject>
// update the simulation
- (void)update;
// get a view for the simulation
- (NSView *)viewWithFrame:(NSRect)frame;
// get the properties for the simulation
// includes "statistics" key, for statistics descriptions
- (NSDictionary *)properties;
// the object to listen to for statistics updates
- (id)statisticsCollector;
@end
Now we can declare that our ControllerOfLife implements this protocol in its header file:
#import "ALifeController.h"
@interface ControllerOfLife : NSObject <ALifeController> {
...
}
Now, we can have a simulationController property of our AppController, defined to be any old object that implements the protocol:
id <ALifeController> simulationController;
However, we still haven't modularized the code enough to keep from hard-coding the name of the actual controller class when initializing the model in our AppController, as above.
The last piece of the puzzle is going to solve this problem and the question of installing new ALife models in one fell swoop: we'll be moving the code for models entirely out of the CocoaBugs project, into their own code bundles---plugins. It turns out that this is going to be really, really easy. Stay tuned!

Leave a comment