Class Factory Methods implementation

后端 未结 2 336
自闭症患者
自闭症患者 2021-01-15 01:08

So I am working my way through the Apple documentation of objective-C (before jumping into iphone development). One of the exercises states that I should create a designated

2条回答
  •  深忆病人
    2021-01-15 01:54

    Excellent explanation by Gabriele Petronella but there is problem.

    +(instancetype)personWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob {
    return [[XYZPerson alloc] initWithNameAndDob:fName last:lName birth:dob];
    }
    
    It should be replaced with 
    +(instancetype)personWithNameAndDob:(NSString *)fName last:(NSString *)lName birth:(NSDate *) dob {
    return [[self alloc] initWithNameAndDob:fName last:lName birth:dob];
    }
    

    Rule: Don’t refer to your own class by name, because you don’t know what the concrete class will be. You’ll inadvertently chop off the ability to extend and override the class through subclassing. Instead, To allocate an instance in a class’s factory method: [self alloc] Reference: http://qualitycoding.org/factory-method/

提交回复
热议问题