以下载功能为例:
1.协议
DownloaderProtocol.h
#import <Foundation/Foundation.h>
@protocol DownloaderProtocol <NSObject>
@required
- (BOOL)checkDownloader;
- (void)startDownload:(id)url;
- (void)stopDownload;
- (void)deleteAllDownloadFile;
//可以使用@optional定义"可选的"接口
//略
@end
2.抽象类
AbstractDownloader.h
#import <Foundation/Foundation.h>
#import "DownloaderProtocol.h"
//遵循协议!!
@interface AbstractDownloader : NSObject <DownloaderProtocol>
//自己的方法
- (void)setDownloadUrl:(NSString *)url;
@end
AbstractDownloader.m
#import "AbstractDownloader.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)checkDownloader
{
AbstractMethodNotImplemented();
}
- (void)startDownload:(id)url
{
AbstractMethodNotImplemented();
}
- (void)stopDownload
{
AbstractMethodNotImplemented();
}
- (void)deleteAllDownloadFile
{
AbstractMethodNotImplemented();
}
//自己的方法
- (void)setDownloadUrl:(NSString *)url
{
NSLog(@"AbstractDownloader's url = %@", url);
}
3.具体实现类
ImageDownloader.h
#import "AbstractDownloader.h"
@interface ImageDownloader : AbstractDownloader
@end
ImageDownloader.m
#import "ImageDownloader.h"
@implementation ImageDownloader
- (BOOL)checkDownloader
{
NSLog(@"ImageDownloader checkDownloader...");
return YES;
}
- (void)startDownload:(id)url
{
NSLog(@"ImageDownloader startDownload...");
}
- (void)stopDownload
{
NSLog(@"ImageDownloader stopDownload...");
}
- (void)deleteAllDownloadFile
{
NSLog(@"ImageDownloader deleteAllDownloadFile...");
}
@end