5

我理解“策略模式”的概念,但我还是有点困惑。

假设我们有一个名为 的类DogDoghas MovementBehaviour(interface) 可以是MovementBehaviourNormaland MovementBehaviourFastMovementBehaviourNormal并且MovementBehaviourFast都包含一个名为move.

问题:从方法中访问狗属性的最佳方法是move什么?MovementBehaviour将狗对象作为代表传递给它是一个坏主意吗?

4

1 回答 1

6

通常,您不应该直接从您的策略对象访问 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 并且仍然完成了您的意图。

于 2010-10-26T03:47:19.480 回答