在休息服务上多态性
我正在尝试清洁和重构我的服务代码,该代码目前看起来像是这样 -
public void generateBalance(Receipt receipt) {
if (receipt.getType().equals(X) && receipt.getRegion.equals(EMEA)) {
// do something to the receipt that's passed
} else if (receiptType.equals(Y)) {
// do something to the receipt
} else if (receipt.getRegion.equals(APAC) {
// call an external API and update the receipt
}....
...
// finally
dataStore.save(receipt);
基本上,此主要服务中有许多条件,这些条件是寻找正在传递的对象中的某些字段。是类型或区域。
我想使用这种设计模式 - htttps> .html 但是,我不确定这对服务课程如何工作。目前,我的休息人员称此特定服务。还如何对“ RecoriptType”和“ region”进行多态性?
有什么方法可以在不同的服务中完成一次收据的所有更新,然后最终将收据保存在一个位置? (也许是基础课?)我对如何开始感到非常困惑。蒂亚!
I am trying to clean and refactor my service code which currently looks like this-
public void generateBalance(Receipt receipt) {
if (receipt.getType().equals(X) && receipt.getRegion.equals(EMEA)) {
// do something to the receipt that's passed
} else if (receiptType.equals(Y)) {
// do something to the receipt
} else if (receipt.getRegion.equals(APAC) {
// call an external API and update the receipt
}....
...
// finally
dataStore.save(receipt);
Basically there's a bunch of conditionals that are in this main service which look for certain fields in the object that is being passed. Either it's the type or the region.
I was looking to use this design pattern- https://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html
However, I am not sure how this would work for a service class. Currently my REST handler calls this particular service. Also how can I do polymorphism for both the "receiptType" and "region"?
Is there a way I can just do all the updates to the receipt once in different services, then finally save the receipt at one location? (maybe a base class?) I am really confused on how to start. TIA!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的班级应该具有相同的行为,那么使用多晶型术变得非常简单。该模式称为策略。让我举个例子。
首先,我们需要使用
enum
。如果您没有enum
,则可以创建一个方法,该方法将根据您的条件返回枚举值:So
enum
将看起来像这样:然后我们需要一个抽象类这将描述派生类的行为:
我们的派生类将看起来以下方式:
此外,我们需要一个工厂,该工厂将基于枚举创建派生的类。因此,我们可以使用 factory模式 进行稍作修改:
然后在行动中看起来会进行多种态度。这样:
更新:
您可以创建一些辅助方法,该方法将返回
enum
基于基于您的
区域逻辑
和recepiptType
:您可以这样称呼:
If your classes should have the same behaviour, then it becomes pretty simple to use polymorpism. The pattern is called as Strategy. Let me show an example.
At first we need to use
enum
. If you do not haveenum
, then you can create a method which will return enum value based on your conditions:So
enum
will look like this:Then we need an abstract class which will describe behaviour for derived classes:
And our derived classes will look this:
Moreover, we need a factory which will create derived classes based on enum. So we can use Factory pattern with a slight modification:
And then polymorpism in action will look like this:
UPDATE:
You can create some helper method which will return
enum
value based onyour logic of
region
andreceiptType
:and you can call it like this: