Reputation: 24912
I'm not sure if I should create an abstract class and a series of descendants that inherit this abstract class, or define a protocol. What's the best practice in Cocoa?
Upvotes: 4
Views: 2394
Reputation: 5057
Allow me to recommend a book called Cocoa Design Patterns it is a very nice book to look up how the Cocoa framework works and what paradigms are used.
Cocoa Design Patterns on Amazon
Upvotes: 2
Reputation: 14558
It depends.
The abstract class + descendants pattern is known as a class cluster in Cocoa terminology. Well-known examples are NSString
and NSArray
. The main advantage of this approach is that you can implement methods on the base class that work in terms of a core set of methods and are inherited; for instance, a subclass of NSString
only needs to implement -length
and -characterAtIndex:
for all public NSString
instance methods to work (although it won’t be very efficient).
The downside of this pattern is that implementations must inherit from the base class, which can be a severe restriction in a single-inheritance language.
A protocol, on the other hand, can be adopted by any class, but can’t provide a base implementation. It’s a lot like a statically-checked version of duck typing; by adopting a protocol you claim you can quack, and by requiring a protocol you can restrict a parameter to quack-capable classes without requiring a specific base class.
If you’re planning to provide a standard set of implementations for your abstraction, you probably want a class cluster. If you want to communicate with an open set of objects implementing your abstraction, you probably want a protocol.
Upvotes: 5