// Person @interfacePerson : NSObject + (instancetype)personWithType:(PersonType)personType; - (void)doWork; @end
@implementationPerson + (instancetype)personWithType:(PersonType)personType { switch (personType) { case PersonTypeA: return [PersonA new]; break; case PersonTypeB: return [PersonB new]; break; case PersonTypeC: return [PersonC new]; break; } }
- (void)doWork { //SubClasses implement this } @end
// // Subclass PersonA @interfacePersonA : Person
@end
@implementationPersonA
- (void)doWork { NSLog(@"do PersonA Work"); }
// // Subclass PersonB @interfacePersonB : Person
@end
@implementationPersonB
- (void)doWork { NSLog(@"do PersonB Work"); }
// // Subclass PersonC @interfacePersonC : Person
@end
@implementationPersonC
- (void)doWork { NSLog(@"do PersonC Work"); }
@end
接口调用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Person *personA = [Person personWithType:PersonTypeA]; Person *personB = [Person personWithType:PersonTypeB]; Person *personC = [Person personWithType:PersonTypeC];
/** * Policies related to associative references. * These are options to objc_setAssociatedObject() */ typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) { OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */ OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. * The association is not made atomically. */ OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied. * The association is not made atomically. */ OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object. * The association is made atomically. */ OBJC_ASSOCIATION_COPY = 01403/**< Specifies that the associated object is copied. * The association is made atomically. */ };