Wednesday, July 21, 2010

Delegate

Usually if we want to add new behavior in an existing object, we do inheritance. For example if we have class Apple below:



If we want the Apple class to have a new behavior such as growAppleInDesert(), we have some options:
1. Put the new method in interface or parent class, IFruit. This will apply to all subclasses, however.
2. Put the new method in Apple class. This can be done; however, if our Apple class is a simple UI, adding the action growAppleInDesert() here will break layering pattern.
3. Subclass Apple to create new class, say DesertApple. This is what OO design pattern suggested.
4. Create new class, say AppleGrowAction which contains growAppleInDesert() , growAppleInMeadow(), etc. Our current Apple object can then refer to the new AppleGrowAction class to call its methods. This is known as delegate.
5. Using "Category" feature of Objective-C. This will be explained later.

Another example is if we want to create a new component from an existing one. We have some options:
1. We can inherit the existing component; however, if the component has so many methods, we will end up having those methods in our class.
2. Put the component as delegate, our new component will only need to call methods in existing component.

In Cocoa Framework, delegate usually implemented as protocol. For example if we have a control UITextField, we will need to implement UITextFieldDelegate protocol in order to handle text field event.



In Java it is common to do (3) or (4), but, in Objective-C, (4) is widely used. It is called delegation because we delegate some tasks to another object.

Category

Category is an Objective-C feature that allows us to extend the capability of a given class. This feature works even if we do not have access to the source code of the class we are extending. When we extend a given class through a category, the extension is inherited by all its subclasses. Of course, the additional methods defined by the category are only seen by our program.

To illustrate this feature, let us extend the NSObject class by adding an instance method to it:

0 comments:

 

©2009 Stay the Same | by TNB