Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Strategy Pattern?

I understand the concept of the "strategy pattern" but I am still a little bit confused.

Let'say we have a class named Dog. Dog has MovementBehaviour (interface) which can be MovementBehaviourNormal and MovementBehaviourFast. MovementBehaviourNormal and MovementBehaviourFast both contain a method named move.

Question: what is the best way to access the dog attributes from the move method? Is it a bad idea to pass the dog object to MovementBehaviour as a delegate?

like image 296
aryaxt Avatar asked Oct 26 '10 03:10

aryaxt


People also ask

What are the objectives of strategic pattern?

The goal of the strategy design pattern is to allow the Client to perform the core algorithm, based on the locally-selected Strategy . In so doing, this allows different objects or data to use different strategies, independently of one another.

What is Strategy pattern in OOP?

In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern. In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.

What is strategy as a pattern?

Strategy as Pattern Rather than being an intentional choice, a consistent and successful way of doing business can develop into a strategy. For instance, imagine a manager who makes decisions that enhance an already highly responsive customer support process.


1 Answers

Generally, you shouldn't be accessing properties on Dog directly from your strategy object. Instead, what you can do is provide a move method that returns a new position based on the old position. So, for example, if you have:

@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

Then, when you instantiate a Dog, you can assign it the NormalDogStrategy and call [dog updatePosition] - the Dog will ask its strategy for its updated position, and assign that to its instance variable itself. You've avoided exposing the internals of Dog to your DogStrategy and still accomplished what you intended.

like image 200
Tim Avatar answered Sep 20 '22 01:09

Tim