直接上代码:(持续更新中....)
SportMan.h 运动员接口,协议
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SportMan <NSObject>
- (void)run;
- (void)jump;
@end
NS_ASSUME_NONNULL_END
Footballer.h 足球运动员实现SportMan协议
#import <Foundation/Foundation.h>
#import "SportMan.h"
NS_ASSUME_NONNULL_BEGIN
@interface Footballer : NSObject<SportMan>
@end
NS_ASSUME_NONNULL_END
Footballer.m
#import "Footballer.h"
@implementation Footballer
- (void)run{
NSLog(@" Footballer run");
}
- (void)jump{
NSLog(@" Footballer jump");
}
@end
SportsAssociation.h 运动员协会
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SportsAssociation <NSObject>
- (id)registerSportMan;
@end
NS_ASSUME_NONNULL_END
FootballAssociation.h 足球运动员协会
#import <Foundation/Foundation.h>
#import "SportsAssociation.h"
NS_ASSUME_NONNULL_BEGIN
@interface FootballAssociation : NSObject<SportsAssociation>
@end
NS_ASSUME_NONNULL_END
FootballAssociation.m
#import "FootballAssociation.h"
#import "Footballer.h"
@implementation FootballAssociation
- (id)registerSportMan{
return [Footballer new];
}
@end
Club.h 俱乐部
#import <Foundation/Foundation.h>
#import "Footballer.h"
NS_ASSUME_NONNULL_BEGIN
@interface Club : NSObject
@property(nonatomic,strong)Footballer *goalkeeper;
@property(nonatomic,strong)Footballer *forwordMan;
@property(nonatomic,strong)Footballer *guardMan;
- (void)test;
@end
NS_ASSUME_NONNULL_END
Club.m
#import "Club.h"
@interface Club()
@end
@implementation Club
- (void)test{
if (self.goalkeeper && self.forwordMan && self.guardMan) {
NSLog(@"队员已齐,开始比赛");
[self.forwordMan run];
[self.forwordMan jump];
}else{
NSLog(@"队员没有到场");
}
}
main 方法
#import <Foundation/Foundation.h>
#import "Club.h"
#import "FootballAssociation.h"
#import "SportManFactory.h"
#import "SportsAssociation.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Club *club = [[Club alloc] init];
FootballAssociation *footballAssociation = [[FootballAssociation alloc] init];
SportManFactory *factory = [[SportManFactory alloc] initWithBuilder:footballAssociation];
club.forwordMan = [factory registerSportMan];
club.goalkeeper = [factory registerSportMan];
club.guardMan = [factory registerSportMan];
// club.forwordMan = [footballAssociation registerSportMan];
// club.goalkeeper = [footballAssociation registerSportMan];
// club.guardMan = [footballAssociation registerSportMan];
[club test];
}
return 0;
}
输出
2021-06-08 22:55:56.328076+0800 Factory[13311:341264] 队员已齐,开始比赛
2021-06-08 22:55:56.328334+0800 Factory[13311:341264] Footballer run
2021-06-08 22:55:56.328357+0800 Factory[13311:341264] Footballer jump
Program ended with exit code: 0