Here is template method pattern , Java and C++ can implement it easily with virtual function. How about Object C to implement this pattern ? Any example in cocoa touch (iOS) ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As jer has already pointed out, all Objective-C methods are essentially virtual. It is a feature of the language which does not quite mesh with other C-like languages. That being said, the basics of the template method pattern can still be achieved in Objective-C, by “manually” forcing subclasses to implement certain functions. For example (using the convention in your linked Wikipedia article):
The above code forces subclasses of
Gameto override the “virtual” methods by throwing an exception the moment one of the base class implementations is called. In effect, this moves the test from the compiler stage (as it would be in C++ or Java) and into the runtime stage (where similar things are often done in Objective-C).If you really want to enforce the rule that subclasses are not allowed to override the
playOneGame:method, you can attempt(*) to verify the correct implementation from within theinitmethod:(*) Note that this code does not result in a 100% rock-solid defense against subclasses which re-implement
playOneGame:, since the very nature of Objective-C would allow the subclass to overrideinstanceMethodForSelector:in order to produce the correct result.