I am working on an rpg type game for the iphone. What I want to do is have an inventory that will only allow you to hold a specific amount of only a specific type of items. I think to do this I’m just going to extend the NSMutableArray and add limits to it. I can’t figure out the best way to do this though. Here’s the idea I have in my head…
Backpack.h
@interface Backpack : NSMutableArray {
Class * arrayClass;
NSMutableArray * array;
int limit;
}
-(id) initWithClass:(Class) type andLimit:(int) num;
@end
Backpack.m
@implementation Backpack
-(id)initWithClass:(Class) type andLimit:(int) num {
arrayClass = type;
limit = num;
array = [NSMutableArray new];
return self;
}
-(void)insertObject:(id) object atIndex:(int) index {
if([object isKindOfClass:arrayClass] && index < limit) {
// Insert it
} else {
// Throw Exception
}
}
@end
Rather than extend NSMutableArray, just create your own class that uses an instance of NSMutableArray to hold items. Your class can have an add method or methods that require items being added to be of a certain class type (or which implement a specific interface). As far as limiting the number of items, in side your addItem method, first check the number of items being held. If it is greater than your limit, then don’t allow the item to be added. Finally, your class can expose a size method (e.g. getSize()) which tells you how many items are already being held internally in the instance of NSMutableArray, that way you can prevent items form being added when your backpack is “full”.
Generally speaking, composition (i.e. composing your own classes from member instances of other classes) is better than extending classes and using inheritance to accomplish the same behavior. If you extend NSMutableArray, for example, then the resulting class is going to expose all of the public methods of that class, in addition to your methods, which leads to a messy class from a code reuse and documentation standpoint.
Finally, your question really isn’t about Java so perhaps this should not be tagged with the Java tag.