今天讲Objective-C除了继承,还有什么好的办法实现类的定制化
Consider Other Alternatives for Class Customization
Categories and class extensions make it easy to add behavior directly to an existing class, but sometimes this isn’t the best option.
One of the primary goals of object-oriented programming is to write reusable code, which means that classes should be reusable in a variety of situations, wherever possible. If you’re creating a view class to describe an object that displays information on screen, for example, it’s a good idea to think whether the class could be usable in multiple situations.
Rather than hard-coding decisions about layout or content, one alternative is to leverage inheritance and leave those decisions in methods specifically designed to be overridden by subclasses. Although this does make it relatively easy to reuse the class, you still need to create a new subclass every time you want to make use of that original class.
Another alternative is for a class to use a delegate object. Any decisions that might limit reusability can be delegated to another object, which is left to make those decisions at runtime. One common example is a standard table view class (NSTableView for OS X and UITableView for iOS). In order for a generic table view (an object that displays information using one or more columns and rows) to be useful, it leaves decisions about its content to be decided by another object at runtime. Delegation is covered in detail in the next chapter, Working with Protocols.
Interact Directly with the Objective-C Runtime
Objective-C offers its dynamic behavior through the Objective-C runtime system.
Many decisions, such as which methods are called when messages are sent, aren’t made at compile-time but are instead determined when the application is run. Objective-C is more than just a language that is compiled down to machine code. Instead, it requires a runtime system in place to execute that code.
It’s possible to interact directly with this runtime system, such as by adding associative references to an object. Unlike class extensions, associated references do not affect the original class declaration and implementation, which means you can use them with framework classes for which you don’t have access to the original source code.
An associative reference links one object with another, in a similar way to a property or instance variable. For more information, see Associative References. To learn more about the Objective-C Runtime in general, see Objective-C Runtime Programming Guide.