OC实战: 抽象类的实现

新博客地址:http://www.veryitman.com/,致力于让开发变得更好!

本篇新地址:http://www.veryitman.com/2019/04/21/%E7%94%A8Objective-C%E5%AE%9E%E7%8E%B0%E6%8A%BD%E8%B1%A1%E7%B1%BB/

这里, 假设你已经明白了

* oc 的继承.

* oc 的多态.其实 oc 里面的方法都是虚方法.

* oc 的协议 protocol.

------------------------------------------------------------------

在多人协助的项目开发中, 一般在设计框架的时候, 我们会约定一些协议, 这些协议是必须要在子类里面实现的.

但是, 有些队友会忘记去实现, 导致一些莫名其妙的问题.

那么, 如果我们能实现类似 c++ 或者 java 的抽象类, 就在一定程度上可以避免这种问题的发生.

-----------------------------------------------------------------

今天. 主要跟大家分享一下, 实现抽象类的思路.~

 

DownloaderProtocol.h 协议

#import <Foundation/Foundation.h>

@protocol DownloaderProtocol <NSObject>

@required

- (BOOL)checkDownloader;

- (void)startDownload:(id)url;

- (void)stopDownload;

- (void)deleteAllDownloadFile;

@end

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);
}

@end


看一下具体实现类.

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

完成了继承抽象类并实现其方法的条件.

使用

    ImageDownloader *downloader = [[ImageDownloader alloc] init];
    [downloader setDownloadUrl:@"url://www.url.com.cn.ht"];
    [downloader checkDownloader];
    [downloader startDownload:nil];
    [downloader stopDownload];
    [downloader deleteAllDownloadFile];


Have fun...

一直致力于让开发更美好的公众号~

 

©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页