I am working on a cocos2d game. It has several classes derived from CCSprite – enemies, projectiles, etc. For each of these subclasses, they need to be further differentiated, e.g., enemy1, enemy2, etc. I can make a class, and then make subclasses of it that can be created through something like [Enemy1 enemy], where + (id)enemy creates an Enemy object, then customizes it and returns it, but what I want to do is tell the Enemy class to create an instance, then give it the properties I want (image, hit points, visible, etc) and then return that. I imagine a method like this…
+ (id)enemyWithType:(int)aType
{
Enemy *enemy = nil;
switch (aType) {
case 1:
// set up the first enemy type
[enemy initWithFile:@"enemy1.png"];
[enemy setVisible:YES];
[enemy setHitPoints:10];
break;
case 2:
// set up the second type
[enemy initWithFile:@"enemy2.png"];
[enemy setVisible:NO];
[enemy setHitPoints:5];
break;
default:
break;
}
Which I would invoke by calling
[Enemy enemyWithType:1];
Or some such. Is this the right way to go about this? I need this to work for all these classes. In practice, my player would have a property like projectileType so that when I fire a projectile, I ask the Projectile class for one of that type.
Basically, yes. It is the factory method pattern. Also you can use derived classes from Enemy such as Zombie class, Dragon class or something like that. It makes the code clean.