I need to develop a strategy pattern where i have a main class with other three classes where i need to refer to the objects of the other three classes using the main class object.To solve this is the strategy pattern will help me? If so please do give me the syntax in Objective-C?
Share
You’ll want to look at Objective-C’s protocol mechanism. Here’s a simple protocol with a single required method:
Then you declare a class that fulfills that protocol:
The implementation must provide the
-executemethod (since it was declared as@required):You can make a similar
ConcreteStrategyBclass, but I’m not going to show it here.Finally, make a context class with a property maintaining the current strategy.
Here is the implementation. The method that delegates to the strategy’s
-executemethod just happens to be called -execute as well, but it doesn’t have to be.Now I’ll make a few instances and put them to use:
The console output shows that the strategy was successfully changed:
Note that if the protocol does not specify
@required, the method is optional. In this case, the context needs to check whether the strategy implements the method:This is a common Cocoa pattern called delegation. For more information on delegation and other design patterns in Cocoa, see this.