简体   繁体   中英

Objective-C: How to decide implementation at runtime

I'm working on app where I need to parse MSR card data to look for a specific user id type of number. The specifics of the parsing will be different for different clients. Ideally I'd like to write separate classes that implement the same interface and choose which one to use at runtime. There's a web component to this as well, so in PHP I just made an interface, then some different classes that implement it, and choose which one to instantiate based on a config value. What's the right way to do this in Objective-C?

I started down the path with a protocol, but can't figure out how to set which implementation the calling code should use. Would I need to import all the implementation classes then write a switch? Seems like there should be an easier way.

Thanks

The protocol approach is a good one. You define the interface in the protocol, then have different concrete classes to implement it. You then have a static method that will decide which one to use and return it, but the caller doesn't know the concrete type, only that it implements your protocol because the return type is the protocol.

This way, all the logic to decide which class to use, and all the knowledge of the different concrete classes is encapsulated in this single factory method and the calling code just says:

// MSRParser is the protocol defining the interface.
// MSRParserHelper is a class with a class method (+)
MSRParser parser = [MSRParserHelper parserForCard:aCard];
[parser doParserThings];

So you see it has no need to know what the class is, only that it conforms to the protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM