且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换条件与多态重构或类似?

更新时间:2023-09-24 23:12:58

我会倾向于从枚举开始 ProjectSize {Small,Medium,Large} 和一个简单的函数返回适当的枚举给一个numberOfManuals。从那里,我会写不同的 ServiceHourCalculators WritingServiceHourCalculator AnalysisServiceHourCalculator (因为它们的逻辑有很大的不同)。每个人都会拿到一个NumberOfManuals,一个ProjectSize,并返回小时数。我可能会创建一个从字符串到ServiceHourCalculator的地图,所以我可以说:

I would tend to start with an enumeration ProjectSize {Small, Medium, Large} and a simple function to return the appropriate enum given a numberOfManuals. From there, I would write different ServiceHourCalculators, the WritingServiceHourCalculator and the AnalysisServiceHourCalculator (because their logic is sufficiently different). Each would take a numberOfManuals, a ProjectSize, and return the number of hours. I'd probably create a map from string to ServiceHourCalculator, so I could say:

ProjectSize projectSize = getProjectSize(_numberOfManuals);
int hours = serviceMap.getService(_serviceType).getHours(projectSize, _numberOfManuals);

这样,当我添加了一个新的项目大小时,编译器会阻止每个服务。这并不是在一个地方都被处理,但是在它再次编译之前都会被处理,这就是我需要的。

This way, when I added a new project size, the compiler would balk at some unhandled cases for each service. It's not all handled in one place, but it is all handled before it will compile again, and that's all I need.

更新
我知道Java,而不是C#(很好),所以这可能不是100%的对,但创建地图将是这样的:

Update I know Java, not C# (very well), so this may not be 100% right, but creating the map would be something like this:

Map<String, ServiceHourCalculator> serviceMap = new HashMap<String, ServiceHourCalculator>();
serviceMap.put("writing", new WritingServiceHourCalculator());
serviceMap.put("analysis", new AnalysisServiceHourCalculator());