mercredi 20 mai 2015

Objective-C: Correct Design Approach?

I have a superclass called Fruit with the following subclasses: Apple, Banana, and Kiwi.

I'd like to do something like this:

Fruit *fruit = [Fruit fruitOfType:Apple];
fruit.treeSize = 
fruit.innerColor = 
[peter pickUpFruit:fruit];

Fruit *otherFruit = [Fruit fruitOfType:Kiwi];
otherFruit.vineSize = 
otherFruit.innerColor =
otherFruit.spikeLength = 
[peter pickUpFruit:otherFruit];

To be more specific, I'd like to create a Fruit instance that can only access properties based on the subclass provided (It wouldn't make sense if you selected Apple and saw fruit.spikeLength).

In my real case, they're all algorithms, which share about 80% of their properties and methods, but also have unique ones that wouldn't make sense on other ones. I think it's also important to note that I have another method that takes in a fruit, and would hate having to type check the correct subclass' class especially when I'm planning on allowing users to subclass and create new algorithms (or fruits in this case).

Facebook's pop framework does this but instead of using subclasses they use keys, and simplify their POPAnimation subclasses down to 3 (POPBasicAnimation, POPSpringAnimation, and POPDecayAnimation).

Example:

POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerBounds];
//toValue will only accept a CGRect value based on the property chosen above
anim.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 400, 400)];
[layer pop_addAnimation:anim forKey:@"size"];

I only need to simplify it to 1... Fruit. Is it possible to use subclasses in this scenario instead of keys? I'm also curious if there's better approaches, and if this has a name, or even a "correct way to go about it".

Sorry if this is confusing.

Aucun commentaire:

Enregistrer un commentaire