I am trying to implement the concept of component programming while writing my iOS game.
In the book "Component Software: Beyond Object-Oriented Programming" by Clemens Szyperski, he mentions a tactic:
(not quote) Start with a Duck class, which adds component Quack. Class Quack implements an interface on whichever object that calls it, the interface specifies a method which uses Quacks quack()
With this setup, Duck has no reference or awareness about Quack except for when it's instantiated, and is never used in Duck thereafter. Other objects can call duckObject.quack() and reach Quack while only being aware of Duck object.
So far, I've been trying to implement this without success. Preferably, Duck should need no more code than instantiation, the rest placed in Quack class. Can this be done in Objective-C (for iOS?), or am I better off leaving COP for other languages?
I don't think there's an exact comparison in ObjC, but it sounds like you want to look into message forwarding. If an object is sent a message to which it doesn't respond, right before an error is signaled, the runtime sends the object forwardInvocation:
, with an NSInvocation
argument that encapsulates the message and arguments.
In forwardInvocation:
, an object can pass along the invocation to another object which does handle that message. This allows a Duck
instance to respond to the message quack
, even though quack
is not implemented by Duck
, by holding a reference to an instance of Quack
, which does implement it:
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
if( [myQuack respondsToSelector:[anInvocation selector]] ){
[anInvocation invokeWithTarget:someOtherObject];
}
else{
[super forwardInvocation:anInvocation];
}
}