在iOS开发中,通常我们需要抽象出一个类,用它来声明一些接口。然后,用一个或者多个继承于他的子类来实现其中的方法。并且,我们不希望这个抽象类,能够实例化出自己的对象,或者调用自己的函数。
这时,我们就需要自己实现一个自己的超抽象类。
//协议接口文件
DownLoadProtocol.h
#import <Foundation/Foundation.h>
@protocol DownLoadProtocol <NSObject>
@required
- (BOOL)checkDownLoad;
- (BOOL)startDownLoad:(id)url;
- (BOOL)stopDownLoad;
- (BOOL)deleteAllDownLoadFile;
@end
//超抽象类
//AbstractDownLoad.h
#import <Foundation/Foundation.h>
#import "DownLoadProtocol.h"
@interface AbstractDownLoad : NSObject <DownLoadProtocol>
- (void)setDownLoadUrl:(NSString*)url;
@end
//AbstractDownLoad.m
//使用@throw 抛出异常,只要是此超抽象类,不允许其调用自己方法和实例化出对象
//智能通过继承此超抽象类的方式来实现此超抽象类的方法
#improt "AbstractDownLoad.h"
#define AbstractMethodNotImplemented() \
@throw [NSException exceptionWithName:NSInternalInconsistencyException \
reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \
userInfo:nil]
@implementation AbstractDownLoader
- (instancetype)init
{
NSAssert(![self isMemberOfClass:[AbstractDownLoader class]], @"AbstractDownloader is an abstract class, you should not instantiate it directly.");
return [super init];
}
- (BOOL)checkDownLoad
{
AbstractMethodNotImplemented();
}
- (BOOL)startDownLoad:(id)url
{
AbstractMethodNotImplemented();
}
- (BOOL)stopDownLoad
{
AbstractMethodNotImplemented();
}
- (BOOL)deleteAllDownLoadFile
{
AbstractMethodNotImplemented();
}
- (void)setDownLoadUrl:(NSString *)url
{
NSLog(@"AbstractDownLoad's url = %@", url);
}
@end
//ImageDownLoad.h
//继承自超抽象类,实现了规定接口
#import "AbstractDownLoad.h"
@interface ImageDownLoad : AbstractDownLoad
@end
//ImageDownLoad.m
//
#import "ImageDownLoad.h"
@implementation ImageDownLoad
- (BOOL)checkDownLoad
{
NSLog(@"ImageDownloader checkDownloader...");
return YES;
}
- (BOOL)startDownLoad:(id)url
{
NSLog(@"ImageDownLoader startDownLoad...");
return YES;
}
- (BOOL)stopDownLoad
{
NSLog(@"ImageDownload stopDownload...");
return YES;
}
- (BOOL)deleteAllDownLoadFile
{
NSLog(@"ImageDownload deleteAllDownloadFile...");
return YES;
}
一个简单的超抽象类就实现了,未完待续。