打印机,实现多态.输入1,使用彩色打印机.输入2,使用黑白打印机
(一)main函数:
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Printer.h"
#import "BlackPrinter.h"
#import "ColorPrinter.h"
int main(int argc, const char * argv[]) {
Person *person = [[Person alloc] init];
Printer *printer1 = [[BlackPrinter alloc] init];
Printer *printer2 = [[ColorPrinter alloc] init];
NSInteger a;
NSLog(@"输入1和2调换打印机");
scanf("%ld",&a);
if (a == 1) {
[person print:printer1];
}
else
[person print:printer2];
return 0;
}
(二)Printer类
#import <Foundation/Foundation.h>
@interface Printer : NSObject
- (void)doPrint;
@end
#import "Printer.h"
@implementation Printer
- (void)doPrint{
NSLog(@"打印机实现了打印");
}
@end
(三)Person类
#import <Foundation/Foundation.h>
#import "Printer.h"
@interface Person : NSObject
- (void)print:(Printer *)printer;
@end
#import "Person.h"
@implementation Person
- (void)print:(Printer *)printer{
[printer doPrint];
}
@end
(四)ColorPrinter类
#import "Printer.h"
@interface ColorPrinter : Printer
@end
#import "ColorPrinter.h"
@implementation ColorPrinter
- (void)doPrint{
NSLog(@"彩色打印机实现了打印");
}
@end
(五)BlackPrinter与ColorPrinter类相似,此处省略.
到此,就解决了这个简单的多态问题
本文出自 “为了学IOS_进击中” 博客,请务必保留此出处http://10577665.blog.51cto.com/10567665/1679567
原文地址:http://10577665.blog.51cto.com/10567665/1679567