第24条:将类的实现代码分散到便于管理的数个分类之中

2018-09-23  本文已影响10人  MrSYLong

类中容易填满各种方法,这个情况下,可以通过“分类”机制,将类的代码按逻辑划入几个分区中,对开发与调试都有好处。

#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject

@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, copy, readonly) NSSet *friends;

- (id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName;

/* 朋友关系 */
- (void)addFriend:(EOCPerson *)person;
- (void)removeFriend:(EOCPerson *)person;
- (BOOL)isFriendsWith:(EOCPerson *)person;

/* 工作 */
- (void)performDaysWork;
- (void)takeVacationFromWork;

/* 玩耍 */
- (void)goToTheCinema;
- (void)goToSportsGame;

@end

使用分类将方法分成几个部分,在一个接口文件中

#import <Foundation/Foundation.h>

@interface EOCPerson : NSObject

@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, copy, readonly) NSSet *friends;

- (id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName;

@end

@interface EOCPerson(FriendsShip)

/* 朋友关系 */
- (void)addFriend:(EOCPerson *)person;
- (void)removeFriend:(EOCPerson *)person;
- (BOOL)isFriendsWith:(EOCPerson *)person;

@end

@interface EOCPerson(Work)

/* 工作 */
- (void)performDaysWork;
- (void)takeVacationFromWork;

@end

@interface EOCPerson(Play)

/* 玩耍 */
- (void)goToTheCinema;
- (void)goToSportsGame;

@end

使用分类,把每个分类提取到各自的文件中。
在使用分类的方法是,主类与分类的头文件一并引入。

// EOCPerson+FriendsShip.h
#import "EOCPerson.h"

@interface EOCPerson (FriendsShip)

/* 朋友关系 */
- (void)addFriend:(EOCPerson *)person;
- (void)removeFriend:(EOCPerson *)person;
- (BOOL)isFriendsWith:(EOCPerson *)person;

@end

// EOCPerson+Work.h
#import "EOCPerson.h"

@interface EOCPerson (Work)

/* 工作 */
- (void)performDaysWork;
- (void)takeVacationFromWork;

@end

// EOCPerson+Play.h
#import "EOCPerson.h"

@interface EOCPerson (Play)

/* 玩耍 */
- (void)goToTheCinema;
- (void)goToSportsGame;

@end

可以把视为“私有”的方法归入名叫Private的分类中,以隐藏实现细节。

上一篇下一篇

猜你喜欢

热点阅读