A Request
類有一個屬性colorType
它可以是不同的顏色。根據顏色的類型,它會涉及到不同的處理方式。如何更好地設計此代碼和邏輯
這裏是控制器代碼:
def colorInstance = Color(params)
//validates and checks the params. Also, based on some logic sets the `colorType` property
//to be appropriate color
if (colorInstnace.validate())
{
colorService.processColor(colorInstance)
}
這裏是colorService
代碼:
void processColor(Color colorInstance) {
if (colorInstance.colorType == "green")
processGreen(colorInstance)
else if (colorInstance.colorType == "red")
processRed(colorInstance)
....
......
}
processGreen(Color colorInstance) {
//common code
//code specific to colortypes that are GREEN
//more common code
}
processRed(Color colorInstance) {
//common code
//code specific to colortypes that are RED
//more common code
}
問題
- 我如何更改代碼的服務,使我不必複製粘貼所有
processXXX
中的代碼方法? - 如何消除
processColor
方法中的if/elseif
?
如果他使用Groovy,他應該繼續使用類型安全的枚舉,而不是整型常量。 – chrylis