大case语句的条码扫描器应用程序设计模式建议

本文关键字:设计模式 应用程序 条码扫描器 case 语句 | 更新日期: 2023-09-27 18:02:55

我正在寻找一些输入,作为一个良好的设计模式/模型,用于重构在制造工厂中使用的windows CE条形码扫描应用程序。试着让它更面向对象,更少过程化

目前,应用程序的大部分功能是由一个主要方法中的大型case语句控制的,私有整数的值决定了通过case的路径。

因为许多扫描是按顺序执行的,所以代码在每次条形码扫描后都循环遍历这个main方法,直到用户退出菜单并选择不同的扫描功能。

对于许多事务类型,代码需要按顺序在主case语句中采用多条路径。例如,"包装"事务要求用户首先扫描他们的id徽章,然后扫描目标容器,然后扫描要在目标容器中包装的物品,所有这些在main方法中都是单独的情况。

在这种情况下,一个非常简单的例子:

private int activeTrans;
private int baseTrans;
private int nextTrans;
btnPack_Click()
{
   nextTransaction = 2
   StartTransaction(1, 1)              
}
StartTransaction(int transId, int transMode)
{
  //determines the initial path(s) to take 
  switch (transMode)
  {
    case 1:  //scan parent 
      activeTrans = 4;
      baseTrans = transId;
      break;
    //a handful of other case statements representing the major types of transactions
    ...
  }
  StartBarcodeRead() //the scanner prepared to scan, once the user scans a barcode, 
                     //the HandleData method is called
}
HandleData()
{
  switch (activeTrans)
  {
    case 1:  //select target container
      DoSomeMethodForTheTargetContainer();
      activeTrans = baseTrans;
    case 2:  //pack in container
      DoThePackingMethod();
    case 3:  //scan id badge
       ValidateIdBadgeScan();
       activeTrans = baseTrans;
       baseTrans = nextTrans;
    ... //about 20 more cases for all the different transactions
}

这似乎是使用命令模式的一个可能的候选,因为每个扫描函数都有可能成为一个"堆栈"或按顺序运行的事务,但我不确定。代码一直运行良好——我只是想尝试重构一下,因为我可以预见,随着需求的变化或增加,代码会变得越来越复杂。

大case语句的条码扫描器应用程序设计模式建议

这是一个非O-O问题,因此寻找O-O设计模式是不合适的(至少在重构的这个阶段)。你需要一个有限状态机,所以设计一个FSM。如果FSM的特定部分看起来仍然过于繁琐或复杂,请为其寻找合适的O-O设计模式。