java中工厂模式用到了反射方法,感觉oc比java更优美一些了。下面就是oc工厂方法的实现:
首先定义三个类分别是Apple,Banana和Pear类继承自Fruit类
@interface Fruit : NSObject
-(void)show;
@end
@interface Apple : Fruit
@end
@interface Banana : Fruit
@end
@interface Pear : Fruit
@end
实现这三个类,都有一个show方法,方便打印出来东西,让我们直观看到结果
@implementation Fruit
-(void)show{
NSLog(@"I am a fruit");
}
@end
@implementation Apple
-(void)show{
NSLog(@"I am an apple");
}
@end
@implementation Banana
-(void)show{
NSLog(@"I am a banana");
}
@end
@implementation Pear
-(void)pear{
NSLog(@"I am a pear");
}
@end
定义一个工厂类,里面有生产水果类的方法:
@interface FruitFactory : NSObject
+(Fruit *)createFruitWithName:(NSString *)fruitName;
@end
实现生产的方法
@implementation FruitFactory
+(Fruit *)createFruitWithName:(NSString *)fruitName{
Class class_ = NSClassFromString(fruitName);
Fruit *theFruit = [(Fruit *)[[class_ alloc]init]autorelease];
if ([theFruit respondsToSelector:@selector(show)]) {
[theFruit show];
}
return theFruit;
}
@end
就两行代码实现生产,一个是根据传入的字符串产生class对象,然后对class对象进行分配内存和初始化,记住要进行类型转化。
然后判断该类有没有show方法,让输出结果更直观。
Fruit *apple = [FruitFactory createFruitWithName:@"Apple"];
一行语句生产了一个苹果类。
打印结果:
I am an apple