基于不同服务构建请求的最佳方式/模式

2024-09-28 05:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大约20个不同的服务,我必须向它们发送请求,它们需要稍微不同的一组标头。在

坏的遗留代码是这样的

row = db.query_for_service()

if row.type == 'foo1'
   // add common headers to request
   // add foo1 specific headers 1
   // add foo1 specific header 2
   // add foo1 specific header 3
else if row.type == 'foo2'
   // add common headers to request
   // add foo2 specific header 1
...
...
...
else if row.type == foo20
   // add common headers to request
   // add foo20 specific header 1
   // add foo20 specific header 2 
   // ...

send_request()

重构它的最佳方法是什么?我考虑过一些可能在这里起作用的模式(策略、构建器),但我不太确定。在

我目前正在学习Java和Python,我想知道这两种语言的解决方案会有什么不同


Tags: toaddifrequesttypecommonelseheaders
2条回答

就我个人而言,我要做的就是沿着这些思路。在

#Put this in the initialisation 
Map foos<row.type,String> = new Map<row.type, String>()
#Populate the map 
map.set('a') = 'headerA specific params x=1'
map.set('b') = 'headerB specific params x=2'
map.set('c') = 'headerC specific params y=3'
map.set ...

Map bars<String,String> = new Map<String,String()
bars.set('fooA') = 'a,b'
bars.set('fooB') = 'a,c'
String commonheader = "HTTP/1.1"


#This would be in a method    
row = db.query_for_service()
String output_header += commonheader
for i in bars.get(fooN).split(','):
    output_header += foos.get(i)
send_request()

类似于伪java/python。地图上会预先填好你需要的东西,然后只需挑出你想要的并附上。在

你应该试试Command模式。在

伪代码如下:

interface Command(){
  void execute();
}

class ConcreteCommandA() implements Command {
  @Override
  void execute(){
    // action 1
  }
}


class ConcreteCommandB() implements Command {
  @Override
  void execute(){
    // action 2
  }
}

并在客户机中使用此结构:

^{pr2}$

等等

相关问题 更多 >

    热门问题