2

I am coming from Java, and I am revisiting the Head First Design Patterns book, (which is the bible for design patterns according to some developers). I am trying to recreate the Duck Simulator from the book by translating Java to obj-c, and this is what I have so far:

https://github.com/ZnelArts/IOSDesignPatterns/tree/master/DesignPatterns/Strategy/DuckSimulator

This simulator uses the Strategy Pattern that is applied using protocols. I have 2 problems with my implementation:

1- I can't have the Duck class to be abstract like in the Java version, on the Java version the method "display()" is abstract and should be implemented by children classes.

2- I had to expose the Duck class properties so children classes have access to them, this is not like in Java in which private properties can be seen by children classes.

What would be the ideal design for this solution?

Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
Hazneliel
  • 531
  • 1
  • 5
  • 16

1 Answers1

1

You are on the right path and you have nicely identified the limitations of Objective-C language in your exercise.

Objective-C lacks the tools for:

1. Having abstract methods

There is a workaround for the abstract method limitation; you can invoke [doesNotRecognizeSelector:] for the abstract method implementations.

Here is an example on a class hierarchy where the base class is abstract. For more details, you can take a look at this thread as well (talks about Template Design pattern in Objective-C).

@interface Life : NSObject

- (void) goThroughTheDay;

- (void) goToWork; // Abstract
- (void) eatLunch; // Abstract
- (void) comeBackHome; // Abstract
- (void) programABitMore; // Abstract

@end

@implementation Life

- (void) goThroughTheDay {

    [self goToWork];
    [self eatLunch];
    [self comeBackHome];
    [self programABitMore];
}

- (void) goToWork { [self doesNotRecognizeSelector:_cmd]; }
- (void) eatLunch { [self doesNotRecognizeSelector:_cmd]; }
- (void) comeBackHome { [self doesNotRecognizeSelector:_cmd]; }
- (void) programABitMore { [self doesNotRecognizeSelector:_cmd]; }

@end

2. Having protected members and methods

There is already a good thread on this one on Stackoverflow, you can check that out.

Community
  • 1
  • 1
Guven
  • 2,280
  • 2
  • 20
  • 34
  • Thanks for your comments, so [self doesNotRecognizeSelector:_cmd] is just a protection for developers accidentally calling the method on the parent class right? – Hazneliel Jun 30 '15 at 14:16
  • Exactly. It has no effect on the compiler. It is just a fair warning (at run time) in case a developer forgets to override one of the abstract methods in his subclass implementation. – Guven Jun 30 '15 at 15:27