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...
- The ConnectionManager is started at startup and it creates the ConnectionQueue
- When a call to the server is needed create a Request object, pass in all required params and add it to the ConnectionQueue
- The queue lets the manager know there's a request that needs to be processed
- The manager removes the request from the queue & makes the call to the server
- Data is received
- The manager creates the response and sends it back to the delegate.
You can see this other post:. I think it can be useful.
精彩评论