Main.m
#import <Foundation/Foundation.h>
#import "Piano.h"
#import "Violin.h"
#import "Actor.h"
/*
乐器(Instrument)分为:钢琴(Piano)、小提琴(Violin)。
各种乐器的弹奏( play )方法各不相同。演奏家可以使用各种乐器。
*/
int main(int argc, const char * argv[])
{
//创建演奏者和乐器
Actor *actor = [[Actor alloc] init];
Piano *piano = [[Piano alloc] init];
Violin *violin = [[Violin alloc] init];
int cmd;
NSLog(@"请输入需要使用的乐器:");
scanf("%d",&cmd);
if (cmd == 1) {
[actor playWithInstrument:piano];
}else if (cmd == 2) {
[actor playWithInstrument:violin];
}else {
NSLog(@"输入有误");
}
return 0;
Actor.h
//使用乐器演奏的方法
- (void)playWithInstrument:(Instrument *)instrument;
Actor.m
//使用乐器演奏的方法
- (void)playWithInstrument:(Instrument *)instrument {
[instrument play];
}
Instrument.h
@interface Instrument : NSObject
//演奏
- (void)play;
Instrument.m
//演奏
- (void)play {
NSLog(@"乐器演奏");
}
Piano.m
//演奏
- (void)play
{
NSLog(@"钢琴演奏");
}
Violin.m
//演奏
- (void)play {
NSLog(@"小提琴演奏");
}