[英]Incoming packets version handling - design issues
考慮數據包來自某個地方。 它具有VERSION字段,傳入數據包有N個可能的VERSIONS。 對於從X到1的每個VERSION數據包,必須使用適當的方法/指令集來處理每個帶有VERSION X的數據包。我完成此任務的唯一想法非常難看,例如:
PACKET p = GetPacketFromSomewhere();
// p.VERSION is 3
if (p.VERSION > 0) {
// things for p.VERSION == 1
}
if (p.VERSION > 1) {
// things for p.VERSION == 2
}
if (p.VERSION > 2) {
// things for p.VERSION == 3
}
// set of if statements up to version N
實際情況是,我的數據包版本號超過10,並且情況仍然可能會發生變化。 當我需要保持向后兼容性時,將添加新的數據包版本。 這段代碼不好,至少我不喜歡它。 你們有更好的主意如何處理這種情況嗎?
使用map
類型的map<unsigned int, function>
其中function
是一個指針,指向所需類型的功能:
typedef void (*function)();
std::map<int,function> handlers;
handlers[1] = &ver1handler;
...
handlers[N] = &verNhandler;
if(handlers.count(p.VERSION))
(*handlers.find(p.VERSION))();
ver[N+1]handler
將定義為:
void ver[N+1]handler(){
ver[N]handler();
// additional handle commands
}
或使用switch
命令,並以相同的方式定義處理程序。
如果處理順序不重要,則可以不間斷地使用switch:
PACKET p = GetPacketFromSomewhere();
// p.VERSION is 3
switch (p.VERSION) {
case 3: {
// things for p.VERSION == 3
}
case 2: {
// things for p.VERSION == 2
}
case 1: {
// things for p.VERSION == 1
}
}
編輯:您還可以使用遞歸函數模板專門化,如下所示:
template<int N>
void proc(PACKET& p){
proc<N-1>(p);
}
template<>
void proc<1>(PACKET& p){
//things for p.VERSION == 1
}
template<>
void proc<2>(PACKET& p){
proc<1>(p)
//things for p.VERSION == 2
}
template<>
void proc<3>(PACKET& p){
proc<2>(p)
//things for p.VERSION == 3
}
然后像這樣調用處理函數:
switch (p.VERSION ) {
case 1: proc<1>(p) break;
case 3: proc<2>(p) break;
case 3: proc<3>(p) break;
default: {
std::cout << "Protocol version not impplemented - using highest known version" << std::endl;
proc<3>(p);
}
這也應該是非常有效的性能明智的選擇(以防您擔心),而您不必擔心協議版本之間的差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.