Skip to content

Typhoon Option Matcher

Jasper Blues edited this page Jul 27, 2015 · 2 revisions

Imagine you have several implementations of a protocol or sub-classes of an abstract base class, and the one that is appropriate to use is not known until run-time. This reasonably common requirement, and its quite easy to configure Typhoon for this.

To return an one definition or another based on information at run-time, create a definition as follows:

- (UIViewController *)dealerBrowserController
{
    return [TyphoonDefinition withOption:[self.coreComponents currentDealers] 
      matcher:^(TyphoonOptionMatcher *matcher) {
        [matcher caseEqual:nil use:[self dealerLoadingViewController]];
        [matcher defaultUse:[self dealerBrowserControllerForLoggedInUser]];
    }];    
}

In the above example one view controller or another is returned, depending on the current state of currentDealers in a collaborating assembly.

With run-time arguments

Its also possible to use a run-time argument to specify which instance is returned. For example:

- (RCAEventInfoBlockDirector *)directorWithClassType:(NSNumber *)classType {
    return [TyphoonDefinition withOption: classType matcher:^(TyphoonOptionMatcher *matcher) {
        [matcher caseEqual:1 use:[self directorForType1]];
        [matcher caseEqual:2 use:[self directorForType2]];
        [matcher defaultUse:[self defaultDirector]];
    }]; 
}

Options can be of any type and the isEqual method will be used for matching.