Reputation: 2088
I recently started working with iOS applications. I could see that, many of the off-the-shelf objects provided by the UIKit uses delegate pattern. For example, a UITableView has a datasource and a delegate for it to provide with data and other other table view functionality.
So, is the underlying design pattern behind this delegate pattern, strategy design pattern? The reason in favor to me is that, in strategy pattern, the delegating object has a reference to a delegate which confirms to a particular interface.
So lets say, I have a class MyDataSource which confirms to the protocol / interface UITableViewDataSource and I implement the behaviors in MyDataSource. And I pass an instance of MyDataSource to UITableView. This is what we do in strategy pattern. So is my understanding right?
Upvotes: 1
Views: 470
Reputation: 5680
What you are referring to is a Cocoa/CocoaTouch design pattern called delegation. I think your understanding is very accurate, however in the example you give at the end of your post it would most likely be the UITableView sending a message to the MyDataSource object and passing itself in as one of the protocol method arguments.
An example would be something like -
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
The above method is implemented by the delegate object and would implement its own strategy. The collectionView that calls this method is passed in as one of the arguments.
Also the UITableView must have a way of accessing MyDataSource object. This is achieved by setting the delegate/dataSource property. It is usually of type id and is weak referenced.
Please view this SO post for more info about the strategy pattern being synonymous to delegation.
Upvotes: 2