iOS 类簇
Person.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject
@property (nonatomic,assign) NSUInteger age;
- (instancetype)personWithAge:(NSUInteger)age;
@end
NS_ASSUME_NONNULL_END
Person.m
#import "Person.h"
@interface __PersonGirl : Person
@end
@implementation __PersonGirl
@end
@interface __PersonWoman : Person
@end
@implementation __PersonWoman
@end
@implementation Person
- (instancetype)personWithAge:(NSUInteger)age
{
if (age <= 18) {
__PersonGirl *girl = [[__PersonGirl alloc] init];
girl.age = age;
return girl;
}else {
__PersonWoman *woman = [[__PersonWoman alloc] init];
woman.age = age;
return woman;
}
}
@end
TestCode
#import "ClassClusterViewController.h"
#import "Person.h"
@interface ClassClusterViewController ()
@end
@implementation ClassClusterViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *person1 = [[Person alloc] personWithAge:15];
Person *person2 = [[Person alloc] personWithAge:30];
NSLog(@"age:%lu,class:%@",(unsigned long)person1.age,[person1 class]);
NSLog(@"age:%lu,class:%@",(unsigned long)person2.age,[person2 class]);
}
@end
打印结果
2021-07-14 14:19:16.392992+0800 TestUI[39422:1747234] age:15,class:__PersonGirl
2021-07-14 14:19:16.393149+0800 TestUI[39422:1747234] age:30,class:__PersonWoman