? ? ? 在iOS開發(fā)中侥加,通常我們需要抽象出一個(gè)類,用它來聲明一些接口粪躬。然后担败,用一個(gè)或者多個(gè)繼承于他的子類來實(shí)現(xiàn)其中的方法。并且镰官,我們不希望這個(gè)抽象類提前,能夠?qū)嵗鲎约旱膶ο螅蛘哒{(diào)用自己的函數(shù)泳唠。
? ? 這時(shí)狈网,我們就需要自己實(shí)現(xiàn)一個(gè)自己的超抽象類。
//協(xié)議接口文件
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 拋出異常笨腥,只要是此超抽象類拓哺,不允許其調(diào)用自己方法和實(shí)例化出對象
//智能通過繼承此超抽象類的方式來實(shí)現(xiàn)此超抽象類的方法
#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
//繼承自超抽象類,實(shí)現(xiàn)了規(guī)定接口
#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;
}
一個(gè)簡單的超抽象類就實(shí)現(xiàn)了脖母,未完待續(xù)士鸥。