最佳台/枚举驱动方法调用系统 [英] Best table / enum driven method calling system

查看:192
本文介绍了最佳台/枚举驱动方法调用系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我在某些格式的外部系统,该系统将发送消息(DB表,消息队列,Web服务)接口。在消息头有消息类型这是一个从1数到20。消息类型定义了与消息的其余部分做。有些事情像新的一样,修改,删除,取消...

Consider I'm interfacing with an external system that will send a message (DB table, message queue, web service) in some format. In the "message header" there is the "MessageType" that is a number from 1 to 20. The MessageType defines what to do with the rest of the message. There are things like new, modified, deleted, canceled...

我的第一个倾向是建立一个枚举和定义所有类型。然后解析数为枚举类型。有了它作为一个枚举我会设置典型的开关箱系统,并呼吁每个消息类型的特定的方法。

My first inclination was to setup an enumeration and define all the types. Then parse the number into an enum type. With it as an enum I would setup the typical switch case system and call a particular method for each of the message types.

一大问题就是维护。

交换机/箱系统是笨重,teadious但是,它真的很简单。

不同的表/配置系统可以是很难为别人神交,并添加新的消息或调整现有消息。

One big concern is maintenance.
A switch / case system is bulky and teadious but, it's really simple.
Various table / configuration systems can be difficult for someone else to grok and add new messages or tweak existing messages.

有关12左右MessageTypes开关/箱系统看起来相当合理。这将是一个合理的分界点切换到一个表驱动的系统?

For 12 or so MessageTypes the switch/case system seems quite reasonable. What would be a reasonable cut-off point to switch to a table driven system?

被认为是什么样的系统最适合处理这些类型的问题?

What kinds of systems are considered best for handling these types of problems?

我设置一个标记为C#和Java在这里,因为它是definitly的通病。有同一问题许多其他语言。

I'm setting a tag for both C# and Java here because it's definitly a common problem. There are many other languages with the same issue.

推荐答案

在Java中,你可以把它一个枚举,给行为不同值(虽然有100个值,我希望每一个类型的行为简单地说,呼唤适当类)。

In Java, you can make it an enum and give behaviour to the different values (although with 100 values, I'd hope that each type of behaviour is briefly, calling out to "proper" classes).

在C#中,你可以有一个地图从价值到一些适当的委托类型 - 。那么当你静态构造图,你可以使用lambda表达式或方法组转换为相应的

In C#, you can have a map from value to some appropriate delegate type - then when you statically construct the map, you can either use lambda expressions or method group conversions as appropriate.

说了这么多,设置达地图将是就像switch语句一样丑陋。如果每个switch语句只是一个方法调用,你可能想尝试这种格式的:

Having said that, setting up the map is going to be just as ugly as a switch statement. If each switch statement is just a single method call, you might like to try this sort of format:

switch (messageType)
{
    case   0: HandleLogin(message);         break;
    case  50: SaveCurrentDocument(message); break;
    case 100: HandleLogout(message);        break;
}



(ETC)。我知道这是对一般的惯例,但它可以像这样奇怪的特殊情况相当整洁。如果您只需要在一个地方的数字,那么就引入常数小点 - 基本上包含数字行有效的的常量定义

这篇关于最佳台/枚举驱动方法调用系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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