What are the differences among Inheritance, Delegation, Category and Observer Pattern in Objective-C? [closed]

StackOverflow https://stackoverflow.com/questions/22344995

I'm new to Objective-C and so am to iOS. I've been developing Android apps - and therefore pretty comfortable with using Inheritance. But in iOS, almost everything is implemented using Delegation. So basically my question is:

  • What is the difference between these four concepts and when to use each? What are the pros and cons of using each?

I searched this question on Stackoverflow, but on no place, I could find those concepts together.

有帮助吗?

解决方案

Inheritance :

Way by which you inherit property of base class to subclass. All public and protected members are inherited to subclass. *Obj-C doesn't have private members so this is not into play.(However you create them by class extensions, even there is some hack to access it).

Delegation :

Way by which you delegate the task of one class to another. The frequent used class and delegates are of UITableViewDelegate. This is always 1-to-1. Callback and return value can be used.

Category :

Way by which you add new methods to an Existing class. When you do this, subclass are also able to use the categorized methods. You never add property using category. *However you can add using associated objects.

Observer Pattern :

A class acts as a broadcaster and broadcasts a message. It doesn't care about who other are its observer or recipient. And all observers receives the notification sent by the observer and start performing on that message. This can be 1-to-0, 1-to-1 or 1-to-many. Even more than one broadcaster can send same notifications hence you can say -to-. Here no call back or return value is sent.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top