Connection Manager: Singleton or not Singleton?

断了今生、忘了曾经 提交于 2019-12-08 07:48:41

问题


My iOS app does a lot of different requests to a Web service. Each request is a call to a method of a ConnectionManager object. When the response arrives from the Web service, a delegate's method is called to notify an interested receiver. Moreover, to maintain the session active, a polling every X seconds is required.

Said so, in your opinion it is better if ConnectionManager is a Singleton or not?

The singleton is simpler (because I do not have to pass a ConnectionManager's reference to all those who need to do a request to the Web service or I do not have to create more ConnectionManagers). Moreover, it is easy to handle the issue of polling: I just add two methods startPolling and stopPolling on the ConnectionManager. But I do not like to use the delegates with a singleton (because there can be only one delegate, and what happens if a response comes when there is not one set?) and at the same time I do not like to use the notifications. I do not like the singleton, too :)

Do you have advice on alternative patterns?


回答1:


I went through similar thinking as you and ended up with this pattern:

ConnectionManager [singleton] - responsible for maintaining a connection to the server and submitting & receiving requests

ConnectionQueue [singleton] - Stores a stack of Requests waiting to be fulfilled

Request - Created each time something is needed from the server. It contains all the request data (urls, params etc) and a reference to the delegate.

Response - A container for the data retrieved from the server along with the original request.

Hooking it all together...

  1. The ConnectionManager is started at startup and it creates the ConnectionQueue
  2. When a call to the server is needed create a Request object, pass in all required params and add it to the ConnectionQueue
  3. The queue lets the manager know there's a request that needs to be processed
  4. The manager removes the request from the queue & makes the call to the server
  5. Data is received
  6. The manager creates the response and sends it back to the delegate.



回答2:


You can see this other post:. I think it can be useful.



来源:https://stackoverflow.com/questions/5896072/connection-manager-singleton-or-not-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!