开发者

Connection Manager: Singleton or not Singleton?

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 s开发者_运维百科et?) 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜