简体   繁体   English

Objective-C:如何在运行时决定实现

[英]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. 我正在开发需要解析MSR卡数据以查找特定用户ID类型的数字的应用程序。 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. 也有一个Web组件,因此在PHP中我创建了一个接口,然后实现了一个不同的类,然后根据配置值选择要实例化的接口。 What's the right way to do this in Objective-C? 在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. 因此,您看到它不需要知道类是什么,只需要知道它符合协议即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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