1.用统一的父类创建类接口穿件对象,具体实现都在各自子类。(UIButton NSArray 都是类簇模式)
// HuEmployee.h
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, HuEmployeeType){
HuEmployeeTypeDeveloper,
HuEmployeeTypeDesigner,
HuEmployeeTypeFinance,
};
@interface HuEmployee : NSObject
@property(nonatomic, copy)NSString *name;
@property(nonatomic, assign)NSUInteger salary;
//1.定义类方法,根据不同type,放回同一父类对象
+(HuEmployee*)employeeWithType:(HuEmployeeType)type;
-(void)doWork;
@end
// HuEmployee.m
#import "HuEmployee.h"
//3.定义各自子类
@interface HuEmployeeDeveloper : HuEmployee
@end
@implementation HuEmployeeDeveloper
-(void)doWork
{
[self writeCode];
}
-(void)writeCode
{
/////
}
@end
@interface HuEmployeeDesigner : HuEmployee
@end
@implementation HuEmployeeDesigner
-(void)doWork
{
[self desighApp];
}
-(void)desighApp
{
/////
}
@end
@interface HuEmployeeFinance : HuEmployee
@end
@implementation HuEmployeeFinance
-(void)doWork
{
[self manageFinance];
}
-(void)manageFinance
{
////
}
@end
@implementation HuEmployee
//2.抽象基类没有特殊标识,一般不定义init方法 也不实现抽象函数,各自在子类里实现
+(HuEmployee*)employeeWithType:(HuEmployeeType)type
{
switch (type) {
case HuEmployeeTypeDeveloper:
return [HuEmployeeDeveloper new];
break;
case HuEmployeeTypeDesigner:
return [HuEmployeeDesigner new];
break;
case HuEmployeeTypeFinance:
return [HuEmployeeFinance new];
break;
default:
break;
}
return nil;
}
-(void)doWork
{
//2.1抛出一个异常,避免在基类里面实现
NSException *e = [NSException
exceptionWithName: @"exceptionName"
reason: @"必须在子类实现改方法"
userInfo: nil];
@throw e;
}
@end
2.判断莫类是否属于是一个特定之类
@interface HuBusinessSupport : NSObject
@end
@implementation HuBusinessSupport
-(void)doSomeTest
{
HuEmployee *employee = [HuEmployee employeeWithType:HuEmployeeTypeDeveloper];
//4.判断是否属于某个子类
// //4.1不用要如下方法检测,一直成立
// if ([employee isMemberOfClass:[HuEmployee class]]){
// //一直为true
// }
//4.2用如下方法 直接用子类判断
if([employee isKindOfClass:[HuEmployeeDeveloper class]])
{
//正确
}
}
@end
如果你发现本文对你有所帮助,如果你认为其他人也可能受益,请把它分享出去。