@fiy-fish
2015-07-19T18:17:07.000000Z
字数 2201
阅读 1306
Objective-c
// main.m
// day09-02-协议
//
// Created by Aaron on 15/7/13.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
//协议
//网络协议
//应用协议
//OC有协议这种语法
//专门用来规定方法
#import "Student.h"
#import "JiangShi.h"
#import "BanZhuRen.h"
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
JiangShi *j = [[JiangShi alloc] init];
Student *std = [[Student alloc] init];
//[std askToTeacher:j];
BanZhuRen *b = [[BanZhuRen alloc] init];
//[std askToTeacher:b];
[std askToSomeOne:j];
Dog *d = [[Dog alloc] init];
[std askToSomeOne:d];
}
return 0;
}
#import "Teacher.h"
@interface BanZhuRen : Teacher
//-(NSString *)banZhuRenAnswer;
@end
#import "BanZhuRen.h"
@implementation BanZhuRen
//-(NSString *)banZhuRenAnswer
//{
// return @"考得非常好";
//}
@end
#import <Foundation/Foundation.h>
//#import "Teacher.h"
//#import "JiangShi.h"
//#import "BanZhuRen.h"
//协议的制定
@protocol StudentScore <NSObject>
//协议里面规定的是方法
-(NSInteger)answerScore;
@end
@interface Student : NSObject
//-(void)askToJiangShi:(JiangShi *)j;
//-(void)askToBanZhuRen:(BanZhuRen *)b;
//-(void)askToTeacher:(Teacher *)teacher;
//让someOne遵守协议
-(void)askToSomeOne:(id <StudentScore>) someOne;
@end
#import "Student.h"
@implementation Student
//-(void)askToJiangShi:(JiangShi *)j
//{
// NSLog(@"讲师,我考了多少分?");
// NSLog(@"讲师回答:%ld",
// [j jiangShiAnswer]);
//}
//
//-(void)askToBanZhuRen:(BanZhuRen *)b
//{
// NSLog(@"讲师,我考了多少分?");
// NSLog(@"班主任回答:%@",
// [b banZhuRenAnswer]);
//}
//-(void)askToTeacher:(Teacher *)teacher
//{
// NSLog(@"考了多少分");
// NSLog(@"考了%ld分",
// [teacher teacherAnswer]);
//}
-(void)askToSomeOne:(id <StudentScore>) someOne
{
NSLog(@"考了多少分");
//协议的作用是统一接口
//统一接口用协议更常用,因为代码更通用,耦合性更低
NSLog(@"考了%ld分",
[someOne answerScore]);
}
@end
import "Teacher.h"
#import "Student.h"
//包含头文件
//遵循协议,<协议名>
@interface JiangShi : Teacher <StudentScore>
//-(NSInteger)jiangShiAnswer;
@end
#import "JiangShi.h"
@implementation JiangShi
//-(NSInteger)jiangShiAnswer
//{
// return 98;
//}
//遵循了协议,就要实现协议的方法
//协议里面的方法,不需要再声明
-(NSInteger)answerScore
{
return 98;
}
@end
#import <Foundation/Foundation.h>
#import "Student.h"
@interface Dog : NSObject <StudentScore>
@end
import "Dog.h"
@implementation Dog
-(NSInteger)answerScore
{
return 10000;
}
@end
#import <Foundation/Foundation.h>
@interface Teacher : NSObject
-(NSInteger)teacherAnswer;
@end
#import "Teacher.h"
@implementation Teacher
-(NSInteger)teacherAnswer
{
return 99;
}
@end