Skip to content

Typhoon Option Matcher

Egor Tolstoy edited this page Nov 2, 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.

More simple approach

If the argument of TyphoonOptionMatcher is a BOOL value, than you can use a simplified syntax:

- (LoggingService *)loggingService {
    return [TyphoonDefinition withOption:@(DEBUG) 
                                     yes:[self debugLoggingService]
                                      no:[self releaseLoggingService]
    ]; 
}