ポリシーモードを使用して、コードのIf elseIfとSwitch Caseの問題を解決します.

13827 ワード

ポリシーモード+ファクトリメソッドは、複数のif elseの代わりにマルチブランチ操作またはSwitch Caseの場合を実現する.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



/**
 *  
 *
 */
@Service
public class CommonSyncService implements ICommonSyncService{
	/**      */
	private static final Logger LOGGER = LoggerFactory.getLogger(CommonSyncService.class);
	
	/**   base_bdm  service    */
	@Autowired
	private IBaseBdmService baseBdmService;
	/**   base_dad  service    */
	@Autowired
	private IBaseDadService baseDadService;
	/**   base_net  service    */
	@Autowired
	private IBaseNetService baseNetService;
	/**   base_sys  service    */
	@Autowired
	private IBaseSysService baseSysService;
	/**   product  service    */
	@Autowired
	private IProductService productService;
	/**   wms  service    */
	@Autowired
	private IWmsService wmsService;
	/**   user  service    */
	@Autowired
	private IUserSysEmployeeService userSysEmployeeService;
	/**   route  service     */
	@Autowired
	private IRouteService routeService;
	
	/**
	 *     -   
	 *           
	 * @param tableName   
	 * @param lastTime       
	 * @param startIndex   
	 * @param pageSize         
	 * @param cdstatus     comp_code(    ,    all)
	 * @return
	 */
	public SyncServerResult commonCallSyncService(String tableName ,String lastTime,
										int startIndex, int pageSize,String cdstatus){
		SyncServerResult result = null;
		
		//      service 
		switch (tableName) {
		  case Constants.TableConstants.BASE_NET_DEPT_BASE_INFO:
			/**
			 * hanyg
			 *       base_net_dept_base_info
			 */
			 result = baseNetService.getDeptBaseInfoSyncServerData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;

		  case Constants.TableConstants.BASE_BDM_QC_TYPE:
			/**
			 * hanyg
			 *        base_bdm_qc_type
			 */
			result = baseBdmService.getQcTypeSyncServerData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.BASE_SYS_COMPANY:
			/** 
			 *   base_sys_company
			 */
			result = baseSysService.getSyncSysCompanyServerData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
			
		  case Constants.TableConstants.BASE_NET_DISTRICT:
			/** 
			 *     base_net_district
			 */
			result = baseNetService.getSyncNetDistrictServerData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
			
		  case Constants.TableConstants.BASE_BDM_FORWARD_ZONE:
			/** 
			 *       base_bdm_forward_zone 
			 */
			result = baseBdmService.getForwardZoneSyncData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.BASE_DAD_DICTIONARY_VALUE:
			/** 
			 *        base_dad_dictionary_value 
			 */
			result = baseDadService.getDictionarySyncData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
			
		  case Constants.TableConstants.BASE_BDM_PRODUCT_TYPE:
			/** 
			 *          base_bdm_product_type 
			 */
			result = baseBdmService.getProductTypeSyncData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
			
		  case Constants.TableConstants.BASE_BDM_PRODUCT_TYPE_APPLY:
			/** 
			 *          base_bdm_product_type_apply 
			 */
			result = baseBdmService.getProductTypeApplySyncData(tableName,lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.BASE_BDM_PRINT_CONFIG:
			/** 
			 *    (    )base_bdm_print_config   
			 */
			result = baseBdmService.getPrintConfigSyncServerData(tableName ,lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.BASE_BDM_WEIGHT_VOLUMN_RATIO:
			/** 
			 *    (      )base_bdm_weight_volumn_ratio   
			 */
			result = baseBdmService.getWeightVolumnRatioSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			
			break;
			
		  case Constants.TableConstants.BASE_DAD_DICTIONARY_CONFIG_VALUE:
			/** 
			 *    (      )base_dad_dictionary_config_value   
			 */
			result = baseBdmService.getDictConfValSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			
			break;
			
		  case Constants.TableConstants.BASE_EACH_COMPANY:
			/** 
			 *    (      )base_each_company   
			 */
			result = baseBdmService.getEachCompanySyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			
			break;
			
		  case Constants.TableConstants.PRODUCT_PRO_MANAGE:
			/** 
			 *   (    )product_pro_manage   
			 */
			result = productService.getProManageSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.PRODUCT_LINE_MAINTENANCE:
			/** 
			 *   (      )product_line_maintenance   
			 */
			result = productService.getProLineSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.PRODUCT_SAL_SERVICE_FEE:
			/** 
			 *   (    )product_sal_service_fee   
			 */
			result = productService.getProSalFeeSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
          case Constants.TableConstants.PRODUCT_SAL_SERVICE_ZONE:
        	/** 
			 *   (        )product_sal_service_zone   
			 */
			result = productService.getProSalZoneSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.PRODUCT_SAL_SPECIAL_GOODS:
			/** 
			 *   (      )product_sal_special_goods   
			 */
			result = productService.getProSalGoodsSyncServerData(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.ROUTE_LINE_CODE:
			/** 
			 *   (    )route_line_code   
			 */
			result = routeService.queryRouteLineCodeByparameter(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.ROUTE_LINE:
			/** 
			 *      route_line   
			 */
			result = routeService.queryRouteLineByparameter(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.USER_SYS_EMPLOYEE:
			/** 
			 *     (user_sys_employee)   
			 */
			result = userSysEmployeeService.queryUserSysEmployeeByparameter(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.WMS_STORAGE:
			/** 
			 *   (  )wms_storage   
			 */
			result = wmsService.queryWmsStorageByparameter(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		  case Constants.TableConstants.WMS_STORAGE_DETAIL:
			/** 
			 *   (    )wms_storage_detail   
			 */
			result = wmsService.queryWmsStorageDetailByparameter(tableName, lastTime, startIndex, pageSize, cdstatus);
			break;
			
		default:
			LOGGER.error("APP        {}   !",tableName);
			
		}
		return result;
	}
	
}

ポリシー+ファクトリ・モードの最適化:
列挙クラス:
import org.apache.commons.lang3.StringUtils;

/**
 *     (            )
 *          
 * 
 * @author 000125
 *
 */
public enum StrategyTypeEnum {
	BASE_NET_DEPT_BASE_INFO("base_net_dept_base_info", "BaseNetDeptBaseInfoStrategy", "      "),
	BASE_BDM_QC_TYPE("base_bdm_qc_type", "BaseBdmQcTypeStrategy", "       "),
	BASE_SYS_COMPANY("base_sys_company", "BaseSysCompanyStrategy", "  "),
	BASE_NET_DISTRICT("base_net_district", "BaseNetDistrictStrategy", "    "),
	BASE_BDM_FORWARD_ZONE("base_bdm_forward_zone", "BaseBdmForwardZoneStrategy", "   "),
	BASE_DAD_DICTIONARY_VALUE("base_dad_dictionary_value", "BaseDadDictionaryValueStrategy", "    "),
	BASE_DAD_DICTIONARY_CONFIG_VALUE("base_dad_dictionary_config_value", "BaseDadDictionaryConfigValueStrategy", "      "),
	BASE_BDM_PRODUCT_TYPE("base_bdm_product_type", "BaseBdmProductTypeStrategy","      "),
	BASE_BDM_PRODUCT_TYPE_APPLY("base_bdm_product_type_apply", "BaseBdmProductTypeApplyStrategy", "      "),
	BASE_BDM_PRINT_CONFIG("base_bdm_print_config", "BaseBdmPrintConfigStrategy", "    "),
	BASE_BDM_WEIGHT_VOLUMN_RATIO("base_bdm_weight_volumn_ratio", "BaseBdmWeightVolumnRatioStrategy", "      "),
	BASE_EACH_COMPANY("base_each_company", "BaseEachCompanyStrategy", "      "),
	PRODUCT_PRO_MANAGE("product_pro_manage", "ProductProManageStrategy", "    "),
	PRODUCT_LINE_MAINTENANCE("product_line_maintenance", "ProductLineMaintenanceStrategy", "      "),
	PRODUCT_SAL_SERVICE_FEE("product_sal_service_fee", "ProductSalServiceFeeStrategy", "     "),
	PRODUCT_SAL_SERVICE_ZONE("product_sal_service_zone", "ProductSalServiceZoneStrategy", "        "), 
	PRODUCT_SAL_SPECIAL_GOODS("product_sal_special_good", "ProductSalSpecialGoodStrategy", "      "),
	ROUTE_LINE_CODE("route_line_code", "RoutLineCodeStrategy", "    "),
	ROUTE_LINE("route_line", "RouteLineStrategy", "  "),
	USER_SYS_EMPLOYEE("user_sys_employee", "UserSysEmployeeStrategy", "   "),
	WMS_STORAGE("wms_storage", "WmsStorageDetailStrategy", "  "),
	WMS_STORAGE_DETAIL("wms_storage_detail", "WmsStorageStrategy", "    "), 
	
	NOT_EXITS_ENUM("", "", "");

	/**
	 *   ,        
	 */
	private String code;
	
	/**
	 *            ,  
	 */
	private String value;
	
	/**
	 *   
	 */
	private String description;
	
	private StrategyTypeEnum(String code, String value, String description) {
		this.code = code;
		this.value = value;
		this.description = description;
	}

	public String getCode(){
        return this.code;
    }

	public String getValue(){
        return this.value;
    }
	
	public String getDescription(){
        return this.description;
    }
	
	public static StrategyTypeEnum getByCode(String code) {

		if (StringUtils.isBlank(code)) {			
			return StrategyTypeEnum.NOT_EXITS_ENUM;
		}
		
        for(StrategyTypeEnum type : StrategyTypeEnum.values()) {
            if(type.getCode().equals(code)) {
                return type;
            }
        }
        return null;
    }
	
	public static StrategyTypeEnum getByValue(String value) {

		if (StringUtils.isBlank(value)) {			
			return StrategyTypeEnum.NOT_EXITS_ENUM;
		}
		
        for(StrategyTypeEnum type : StrategyTypeEnum.values()) {
            if(type.getValue().equals(value)) {
                return type;
            }
        }
        return null;
    }

}

ポリシーインタフェース:
 
/**
 *     
 *                          ,
 *          +                   
 *    
 * 
 * @author 000125
 *
 */
public interface SyncStrategy {
	/**
	 *       ,              
	 * 
	 * @param tableName -         
	 * @param lastTime -      ,       
	 * @param startIndex -   
	 * @param pageSize -         
	 * @param cdstatus -     comp_code(    ,    all)
	 * @return
	 */
	public Object doOperate(String tableName, String lastTime, int startIndex, int pageSize, String cdstatus);

}

ポリシー実装クラス:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *           ,         (    )
 * 
 * @author 000125
 *
 */
public class BaseBdmForwardZoneStrategy implements SyncStrategy { 
	/**      */
	private static final Logger LOGGER = LoggerFactory.getLogger(BaseBdmForwardZoneStrategy.class);
	
	/**
	 *       base_bdm_forward_zone 
	 */
	@Override
	public Object doOperate(String tableName, String lastTime, int startIndex, int pageSize, String cdstatus) {
		// TODO                        
		IBaseBdmService baseBdmService = SpringContextUtil.getBean("baseBdmServiceImpl", BaseBdmServiceImpl.class);
		if (baseBdmService == null){
			LOGGER.error("  Spring Bean    !");
			return null;
		}
		return baseBdmService.getForwardZoneSyncData(tableName, lastTime, startIndex, pageSize, cdstatus);
	}

}

工場クラス:


import org.apache.commons.lang3.StringUtils;


/**
 *           
 * 
 * @author 000125
 *
 */
public class StrategyFactory {
	
	private StrategyFactory() {
		
	}
	
	public static SyncStrategy getStrategy(String code){
	    
		String clazzPrefix = "com.appsync.core.gof.strategy.impl.";
        String clazzName = StrategyTypeEnum.getByCode(code).getValue();
        
        SyncStrategy strategy = null;        
        if (StringUtils.isNotBlank(clazzName)) {
        	try {
        		//          
                strategy = (SyncStrategy) Class.forName(clazzPrefix + clazzName).newInstance();
            } catch (Exception e) {
                e.printStackTrace(); 
                System.out.println("      ");
            } 
		}
		              
        
        return strategy;
    }

}

 
クライアントクラス(ユニットテスト例):
public class BaseTest extends SpringTestCase{
		
	@Test
	public void queryPrintConfigSql(){
		
		String tableName="base_bdm_forward_zone",
			   lastTime="2018-01-10 00:00:00",
			   cdstatus="all";
		int startIndex=1; int pageSize=10; 
		
		try {
			HystrixRequestContext.initializeContext();
			//    
		 
			SyncServerResult result = SyncStrategyFacade.sync(tableName, lastTime, startIndex, pageSize, cdstatus);
			
			 
			String jsonResult = JSONObject.toJSONString(result);
			System.out.println("jsonResult="+jsonResult);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	 

}

上のコードから、ポリシーモードは具体的なアルゴリズムを具体的なポリシーロールの内部にカプセル化し、拡張性を強化し、実現の詳細を隠していることがわかります.継承の代わりに実装され、if-elseというメンテナンスしにくい条件文を回避します.もちろん、ポリシーモードは独立したポリシー実装のため、システム内に多くのポリシークラスが増加していることも見ることができます.クライアントにとって、ドライブの特定のポリシーと、特定のポリシーを選択する条件を知る必要があります.