Per usare il Pattern della strategia in Objective-C, penso che sia principalmente dal selector .
Per omettere if...else
, utilizzare il runtime Objective-C, convertire la corrispondenza delle stringhe per selezionare il selettore (Strategia).
Ho capito bene?
Ecco la demo: Pattern di strategia in ResponderChain Communication Pattern.
crea un router per utilizzare la comunicazione ResponderChain
#import "UIResponder+Router.h"
@implementation UIResponder (Router)
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
[[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
}
@end
mittente dell'evento:
[self routerEventWithName:kBLGoodsDetailBottomBarEventTappedBuyButton userInfo:nil];
Ricevitore di eventi:
#pragma mark - event response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
/*
do things you want
*/
// call the upper ,by ResponderChain
// [super routerEventWithName:eventName userInfo:userInfo];
}
Ecco la parte strategica:
quando le sorgenti di eventi sono molte, usa la strategia per specificare la situazione concreta.
#pragma mark - event response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
NSInvocation *invocation = self.eventStrategy[eventName];
[invocation setArgument:&userInfo atIndex:2];
[invocation invoke];
// call the upper ,by ResponderChain
// [super routerEventWithName:eventName userInfo:userInfo];
}
- (NSDictionary <NSString *, NSInvocation *> *)eventStrategy
{
if (_eventStrategy == nil) {
_eventStrategy = @{
kBLGoodsDetailTicketEvent:[self createInvocationWithSelector:@selector(ticketEvent:)],
kBLGoodsDetailPromotionEvent:[self createInvocationWithSelector:@selector(promotionEvent:)],
kBLGoodsDetailScoreEvent:[self createInvocationWithSelector:@selector(scoreEvent:)],
kBLGoodsDetailTargetAddressEvent:[self createInvocationWithSelector:@selector(targetAddressEvent:)],
kBLGoodsDetailServiceEvent:[self createInvocationWithSelector:@selector(serviceEvent:)],
kBLGoodsDetailSKUSelectionEvent:[self createInvocationWithSelector:@selector(skuSelectionEvent:)],
};
}
return _eventStrategy;
}