码迷,mamicode.com
首页 > 其他好文 > 详细

自定义类工厂方法

时间:2017-03-18 23:47:08      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:name   苹果   而不是   span   sar   nsarray   允许   写法   nsstring   

1.自定义工厂方法

  • 什么是工厂方法(快速创建方法)

    • 类工厂方法是一种用于分配、初始化实例并返回一个它自己的实例的类方法。类工厂方法很方便,因为它们允许您只使用一个步骤(而不是两个步骤)就能创建对象. 例如new
  • 自定义类工厂方法的规范

    • (1)一定是+号开头
    • (2)返回值一般是instancetype类型
    • (3)方法名称以类名开头,首字母小写
  • 示例

+ (id)person;
+ (id)person
{
    return  [[Person alloc]init];
}

+ (id)personWithAge:(int)age;
+ (id)personWithAge:(int)age
{
    Person *p = [[self alloc] init];
    [p setAge:age];
    return p;
}
  • apple中的类工厂方法
其实苹果在书写工厂方法时也是按照这样的规划书写
    [NSArray array];
    [NSArray arrayWithArray:<#(NSArray *)#>];
    [NSDictionary dictionary];
    [NSDictionary dictionaryWithObject:<#(id)#> forKey:<#(id<NSCopying>)#>];
    [NSSet set];
    [NSSet setWithObject:<#(id)#>];

2.子父类中的类工厂方法

  • 由于之类默认会继承父类所有的方法和属性, 所以类工厂方法也会被继承
  • 由于父类的类工厂方法创建实例对象时是使用父类的类创建的, 所以如果子类调用父类的类工厂方法创建实例对象,创建出来的还是父类的实例对象
  • 为了解决这个问题, 以后在自定义类工厂时候不要利用父类创建实例对象, 改为使用self创建, 因为self谁调用当前方法self就是谁

  • 示例

interface Person : NSObject
+ (id)person;
@end

@implementation Person
+ (id)person
{
    return  [[Person alloc]init];
}
@end

@interface Student : Person
@property NSString *name;
@end

@implementation Student

@end

int main(int argc, const char * argv[])
{
    Student *stu = [Student person];// [[Person alloc] init]
    [stu setName:@"lnj"]; // 报错, 因为Person中没有setName
}
  • 正确写法
@interface Person : NSObject
+ (id)person;
@end

@implementation Person
+ (id)person
{
//   return  [[Person alloc]init];
//     谁调用这个方法,self就代表谁
//    注意:以后写类方法创建初始化对象,写self不要直接写类名
    return  [[self alloc]init];
}
@end

@interface Student : Person
@property NSString *name;
@end

@implementation Student
@end

int main(int argc, const char * argv[])
{
    Student *stu = [Student person];// [[Student alloc] init]
    [stu setName:@"lnj"];
}

 

自定义类工厂方法

标签:name   苹果   而不是   span   sar   nsarray   允许   写法   nsstring   

原文地址:http://www.cnblogs.com/xufengyuan/p/6576416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!