Design Patterns – Adhering to a Protocol and Being a Subclass Simultaneously

design-patternsinterfacesobjective c

In objective C, I have a situation where I would like to have an abstract protocol (interface) with 5 methods and 4 properties, but at the same time, I'd like to have a common implementation of 3 of those 5 methods.

So my question is, is it ok to

1) have just an interface declaration with all the method and property declarations,

2) have a base class that adheres to that protocol (implements that interface) but also provides a common implementation of some of those classes, and only has empty stub method implementations for the rest of the methods, and then finally,

3) have a bunch of subclasses (from that base class), that will conform to that protocol – but – also inherit common method implementations -and – implement on their own those stub methods?

Best Answer

This is the pattern that is often used to address the lack of abstract classes in Objective C.

It is very common for the missing method stubs of the base implementation to raise an exception, to make sure that you catch incomplete implementations. See this answer on stack overflow for details of how it is commonly done.

Related Topic