An abstract class or protocol, what is recommended by Cocoa?

I'm not sure if I should create an abstract class and a series of descendants that inherit this abstract class, or define a protocol. What is the best practice at Cocoa?

+4
source share
2 answers

It depends.

An example of an abstract class + descendants is known as a cluster of classes in Cocoa terminology. Known examples are NSString and NSArray . The main advantage of this approach is that you can implement base class methods that work in terms of the main set of methods and are inherited; for example, a subclass of NSString should implement only -length and -characterAtIndex: for all public methods of an NSString instance (although it will not be very efficient).

The disadvantage of this template is that implementations must inherit from the base class, which can be a serious limitation in a language with a single inheritance.

A protocol, on the other hand, can be adopted by any class, but cannot provide a basic implementation. Its a lot like a static version of duck typing; by adopting a protocol that you claim you can stun, and by requiring a protocol, you can limit the parameter to quack compatible classes without requiring a specific base class.

If you plan on providing a standard set of implementations for your abstraction, you probably need a class cluster. If you want to communicate with an open set of objects that implement your abstraction, you probably need a protocol.

+5
source

Let me recommend a book called Cocoa Design Patterns, this is a very good book to see how Cocoa framework works and what paradigms are used.

Cocoa Design Patterns on Amazon

+2
source

Source: https://habr.com/ru/post/1346448/


All Articles