views:

74

answers:

2

Hello,

In C++ there is a template method idiom when base class implements all its algorithms but factors out some tiny little differences (usually having to deal with data formats, etc) for subclasses to implement in the form of protected virtual methods that are not accessible to hierarchy clients.

What is the most natural way to express the same idiom in Objective-C?

Thank you.

+1  A: 

I would create a separate header file with a category. You could name that category Protected:

@interface MyClass(Protected)
// Place your "protected" methods here.
@end

Normal class users would not #import this file, only the main class file. But the implementation and subclasses would the also #import the header file containing the Protected category.

If the methods are optional, you could instead make use of a protocol:

@protocol MyClassProtected
// Required methods here.
@optional
// Optional methods here.
@end

I feel that this not as good a solution as the category but it'd work.

Then, the third way is to simply refrain to convention: name your protected methods accordingly:

@interface MyClass {
}

// This method is not to be called by users, but subclasses may
// overwrite to do something else.
- (void) protected_someMethodDoingFoo;
@end
DarkDust
A: 

It sounds to me like you are asking for the Java concept of an Abstract class. Does this discussion on abstract Objective C classes help?

Derek Clarkson