处理第三方API时,正确的系统设计是什么? [英] What is the correct system design when dealing with third party API?

查看:142
本文介绍了处理第三方API时,正确的系统设计是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇由Joubert撰写的博文打开了我的眼睛。我在Java和其他语言中处理了很多设计模式。但是Objective-C是一个相当独特的语言。

This blog post by Joubert just opened my eyes. I have dealt with a lot of design patterns in Java and other languages. But Objective-C is a rather unique language.

我们假设在一个项目中我们与第三方API,如Dropbox或Facebook交谈。到目前为止我一直在做的是将与第三方API有关的所有内容组合到单例类中。所以我可以从任何地方访问我的视图控制器中的类。我可以去举个例子: [[DropboxModel sharedInstance] uploadFile:aFile]

Let's say that in a project we talk with a third party API, like Dropbox or Facebook. What I've been doing so far is to combine everything that has to do with the third party API into a singleton class. So I can access the class from anywhere in my view controllers. I can just go for example: [[DropboxModel sharedInstance] uploadFile:aFile]

,这是不高效的,导致意大利面条代码和坏单元测试。那么,什么是最好的方式设计系统,使其模块化和易于使用?

However as the blog post noted, this isn't efficient and leads to spaghetti code and bad unit testing. So what is the best way to design the system so that it's modular and easy to use?

推荐答案

单独导致意大利面条代码并且效率低下。但是,单元测试问题是合法的,单例确实减少了模块性,因为它们只是一些奇特的全局变量。

I would dispute the idea that singletons lead to spaghetti code and are inefficient. However, the unit testing problem is legitimate and singletons do reduce modularity since they are really just fancy global variables.

我喜欢Joubert将singleton实例注入到控制器s)从应用程序委托(它本身是一个单例,一个)。我认为同样的方法将为你工作。

I like Joubert's idea of injecting the singleton instance into the controller(s) from the app delegate (which is itself a singleton, ahem). I think the same approach would work for you.

在这种情况下,我通常可以在单元测试中使用不同的存根对象,定义一个协议来表示API,使我的真正API对象符合它和我的存根API对象。我使用单元测试中的存根和应用程序中的真实对象。

What I normally do in these situations where I might want to use a different stub object in unit tests is define a protocol to represent the API and make my "real" API object conform to it and also my stub API object. I use the stub in the unit tests and the real object in the app.

这篇关于处理第三方API时,正确的系统设计是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆