/*
类工厂方法:用于分配、初始化实例并返回一个它自己实例的方法,允许你使用一个步骤就能创建对象,比如new 方法
用于快速创建对象的类方法, 我们称之为类工厂方法
类工厂方法中主要用于 给对象分配存储空间和初始化这块存储空间
1、是类方法,必须以 + 开头;
2、返回类型是 instancetype/id类型;
3、方法名是首字母小写的类名。
*/
//Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property age;
//无参工厂类方法
+ (instancetype)person;
//有参数工厂类方法
+ (instancetype)personWithAge:(int)age;
@end
//Person.m
#import "Person.h"
@implementation Person
+ (instancetype)person
{
//return [[Person alloc] init];
// 注意: 以后但凡自定义类工厂方法, 在类工厂方法中创建对象一定不要使用类名来创建,要使用self来创建
// self在类方法中就代表类对象,谁调用当前方法, self就代表谁
return [[self alloc] init];
}
+ (instancetype)personWithAge:(int)age
{
Person *p = [[Person alloc] init];
p.age = age;
return p;
}
@end
//Student.h
#import <Foundation/Foundation.h>
@interface Student : Person
@property int no;
@end
//Student.m
#import "Student.h"
@implementation Student
@end
//main.m
#import <Foundataion/Foundation.h>
#import “Person.h”
int main(int argc, const char * argv[])
{
Person *p = [Person person];
p.age = 44;
NSLog(@"age = %i",p.age);
Student *stu = [Student person];
stu.no = 22; //person 方法 要使用self 来创建,否则这里会报错:父类的类中 没有 no 属性,要用self来创建 指向子类Student
NSLog(@"age = %i",stu.no);
return 0;
}
参考:
1.
Object-C 工厂方法
http://www.cnblogs.com/aleuxqin/p/5367851.html
2.