写写学习多态时的例子:打印机有很多种,彩色打印机、黑色打印机、激光打印机……去做打印这件事情就需要对应不同的打印机,若有一个Person类,那么Person类中就需要定义很多种方法。每增加一种新的打印机,都要修改Person类,以增加相应的打印方法,代码可扩展性和可维护性很差。多态可以解决的问题是,子类覆盖父类的方法,每个子类实现的功能不相同,通过调用相同的方法来完成不同的事情。
以两种打印机(黑白打印机&彩色打印机)为例,很简洁:
Printer类:
Printer.h:
#import <Foundation/Foundation.h>
@interface Printer : NSObject
-(void) print;
@end
Printer.m:
#import "Printer.h"
@implementation Printer
-(void) print
{
NSLog(@"打印机打印");
}
@end
ColorPrinter类:
ColorPrinter.h:
#import "Printer.h"
@interface ColorPrinter : Printer
@end
ColorPrinter.m:
#import "ColorPrinter.h"
@implementation ColorPrinter
//重写父类print方法
-(void) print
{
NSLog(@"打印彩色效果");
}
@end
BlackPrinter类
BlackPrinter.h:
#import "Printer.h"
@interface BlackPrinter : Printer
@end
BlackPrinter.m:
#import "BlackPrinter.h"
@implementation BlackPrinter
//重写父类print方法
-(void) print
{
NSLog(@"打印黑白效果");
}
@end
Person类
Person.h:
#import <Foundation/Foundation.h>
#import "Printer.h"
@interface Person : NSObject
-(void) doPrint: (Printer *) printer;
@end
Person.m:
#import "Person.h"
@implementation Person
-(void) doPrint:(Printer *)printer
{
[printer print];
}
@end
下面是main文件里的实现
#import "Person.h"
#import "ColorPrinter.h"
#import "BlackPrinter.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Printer *blackPrinter = [[BlackPrinter alloc] init];
Printer *colorPrinter = [[ColorPrinter alloc] init];
Person *me = [[Person alloc] init];
[me doPrint:blackPrinter];
[me doPrint:colorPrinter];
}
return 0;
}