通常,您不应该直接从您的策略对象访问 Dog 上的属性。相反,您可以做的是提供一个 move 方法,该方法根据旧位置返回一个新位置。因此,例如,如果您有:
@interface Dog : NSObject {
NSInteger position;
DogStrategy * strategy;
}
@property(nonatomic, assign) NSInteger position;
@property(nonatomic, retain) DogStrategy * strategy;
- (void)updatePosition;
@end
@implementation Dog
@synthesize position, strategy;
- (void)updatePosition {
self.position = [self.strategy getNewPositionFromPosition:self.position];
}
@end
@interface DogStrategy : NSObject { }
- (NSInteger)getNewPositionFromPosition:(NSInteger)pos;
@end
// some parts elided for brevity
@interface NormalDogStrategy : DogStrategy { }
@end
@implementation NormalDogStrategy
- (NSInteger)getNewPositionFromPosition:(NSInteger)pos {
return pos + 2;
}
@end
然后,当您实例化 Dog 时,您可以为其分配 NormalDogStrategy 并调用[dog updatePosition]
- Dog 将询问其策略以获取其更新的位置,并将其分配给其实例变量本身。您避免将 Dog 的内部结构暴露给 DogStrategy 并且仍然完成了您的意图。