Main.m
#import <Foundation/Foundation.h> #import "ColorPrinte.h" #import "Blackprinter.h" #import "ThreeDPrinter.h" #import "Printer.h" #import "Person.h" int main(int argc, const char * argv[]) { /* //使用彩色打印机打印 Person *person = [[Person alloc] init]; // ColorPrinte *colorPrint = [[ColorPrinte alloc] init]; Blackprinter *blackPrint = [[Blackprinter alloc] init]; // [person printWithColorkPrint:colorPrint]; //使用黑白打印机打印 // [person printWithBlackPrint:blackPrint]; //使用3D打印机 ThreeDPrinter *threeDPrint = [[ThreeDPrinter alloc] init]; [person printWith3DPrint:threeDPrint]; */ /* 人 *人 = [男人 alloc]init]; */ //用父类声明的变量指向子类的对象 // Printer *printer = [[ColorPrinte alloc] init]; // [printer print]; //--------------------多态--------------------- Person *person = [[Person alloc] init]; //创建三个打印机 ColorPrinte *colorPrint = [[ColorPrinte alloc] init]; Blackprinter *blackPrint = [[Blackprinter alloc] init]; ThreeDPrinter *threeDPrint = [[ThreeDPrinter alloc] init]; int cmd; while (1) { NSLog(@"请输入选择的打印机类型(1、黑白,2、彩色,3、3D):"); scanf("%d",&cmd); if (cmd == 1) { [person printer:blackPrint]; }else if (cmd == 2) { [person printer:colorPrint]; }else if (cmd == 3) { [person printer:threeDPrint]; }else { NSLog(@"输入有误"); } } /* 多态: 1、继承 2、方法重写 3、父类声明的变量指向子类对象 */ return 0;
Person.h
#import <Foundation/Foundation.h> #import "Blackprinter.h" #import "ColorPrinte.h" #import "ThreeDPrinter.h" #import "Printer.h" @interface Person : NSObject /* //使用黑白打印机 - (void)printWithBlackPrint:(Blackprinter *)blackPrint; //使用彩色打印机 - (void)printWithColorkPrint:(ColorPrinte *)colorPrint; //使用3D打印机 - (void)printWith3DPrint:(ThreeDPrinter *)threeDPrint; */ - (void)printer:(Printer *)printer;
Person.m
#import "Person.h" @implementation Person /* //使用黑白打印机 - (void)printWithBlackPrint:(Blackprinter *)blackPrint { //调用黑白打印机的打印方法 [blackPrint print]; } //使用彩色打印机 - (void)printWithColorkPrint:(ColorPrinte *)colorPrint { //调用彩色打印机的打印方法 [colorPrint print]; } //使用3D打印机 - (void)printWith3DPrint:(ThreeDPrinter *)threeDPrint { [threeDPrint print]; } */ - (void)printer:(Printer *)printer { [printer print]; }
Printer.h
- (void)print;Printer.m
- (void)print { NSLog(@"打印机打印纸张"); }
BlackPrinter.m
- (void)print { NSLog(@"黑白打印机打黑白印纸张"); }
ColorPrinter.m
- (void)print { NSLog(@"彩色打印机打印彩色纸张"); }
ThreeDPrinter.m
- (void)print { NSLog(@"3D打印机打印3D"); }