Thursday, March 3, 2016

Categories vs Class Extensions vs Class Clusters

We can use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing.

One can also use categories of your own classes to:

Distribute the implementation of your own classes into separate source files—for example, you could group the methods of a large class into several categories and put each category in a different file.

Declare private methods.
You add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are an extension to a class declared elsewhere, not a new class.

#import "SystemClass.h"

@interface SystemClass (CategoryName)
// method declarations
@end

#import "MyClass.h"

@interface MyClass (PrivateMethods)
// method declarations
@end

@implementation MyClass
// method definitions
@end


A class cluster is an architecture that groups a number of private, concrete subclasses under a public, abstract superclass. The grouping of classes in this way provides a simplified interface to the user, who sees only the publicly visible architecture. Behind the scenes, though, the abstract class is calling up the private subclass most suited for performing a particular task. For example, several of the common Cocoa classes are implemented as class clusters, including NSArray, NSString, and NSDictionary.

You create and interact with instances of the cluster just as you would any other class. Behind the scenes, though, when you create an instance of the public class, the class returns an object of the appropriate subclass based on the creation method that you invoke. (You don’t, and can’t, choose the actual class of the instance.)

NSString *string1 = @"UTF32.txt";
NSString *string2 = [NSHomeDirectory() stringByAppendingPathComponent:string1];
NSTextStorage *storage = [[NSTextStorage alloc] initWithString:string2];
NSString *string3 = [storage string];

Benefits
The benefit of a class cluster is primarily efficiency. The internal representation of the data that an instance manages can be tailored to the way it’s created or being used. Moreover, the code you write will continue to work even if the underlying implementation changes.


references:

No comments:

Post a Comment