1

我正在编写一个客户端,它通过 TCP 从服务器接收一组不同的消息。我创建了一个简单的测试类,它能够连接到服务器并以 NSData 块的形式接收消息。但现在我被困在如何从这里开始并需要一些设计建议。

我的一个想法是为每条消息创建一个协议,通知委托接收到的消息类型和包含消息的对象:

协议

-(void)didReceiveLifesign:(LifesignMessage*)message;
-(void)didReceiveLocation:(LocationMessage*)message;
...

解析器

-(void)didReceiveData:(NSData*)data {
    int type = getType(data);
    switch(type) {
        case 0: [self.delegate didReceiveLifesign:parseLifesign(data); break;
        case 1: [self.delegate didReceiveLocation:parseLocation(data); break;
        ...
    }
}

但是随着消息数量的增加,我发现这个解决方案很混乱。有没有更漂亮的方法来做到这一点?

4

1 回答 1

1

Each time you add a new type of message to the system, you will be adding new code to handle that particular type. You cannot get away from that. So, the place you can really abstract-out right now is the dispatching: the switch statement, in your case.

If very few new message-types will be added in the future, the simplest approach may be the one you have already taken: simply add a new "case" each time.

An alternate approach is to allow other code to register as a "listener"/"callback". That makes the dispatching generic. The logic becomes:

  • Find the message type
  • Dispatch to all registered callbacks/listeners

The new "problem" would be: you will now need to register each listener at some point. This would be sdone during some type of initialization. it may not be worth it if your message dispatcher is basically part of the overall app, and is not to be used elsewhere.

于 2013-02-25T16:43:53.137 回答