oc中的工厂方法很好用。要实例化对象很方便,即写一个静态方法(类方法)进行实例化。
1.定义成员变量
@property (nonatomic,assign)int age;
@property (nonatomic,copy)NSString* name;
2.写“构造方法”
- (instancetype) initWithAge:(int)newAge andName:(NSString *)newName;
实现它:
-(instancetype)initWithAge:(int)newAge andName:(NSString *)newName{
self = [super init];
if (self) {
self.age = newAge;
self.name = newName;
}
return self;
}
3.写静态方法
+ (Person *)personWithAge:(int)newAge andName:(NSString *)newName;
实现它:
+(Person *)personWithAge:(int)newAge andName:(NSString *)newName{
return [[Person alloc] initWithAge:newAge andName:newName];
}
4.调用工厂方法:
Person *p1 = [Person personWithAge:20 andName:@"Denny"];
NSLog(@"%d,%@",p1.age,p1.name);
5.输出结果:
2014-06-14 23:53:24.387 lesson01-工厂方法[782:303] 20,Denny
就搞定了。