英文:
Avoiding if-else with Protobuf generated enums using visitor pattern
问题
假设我有一个如下所示的 proto 对象:
oneof sample {
string str = 1;
int64 i = 2;
...(oneof 内的许多其他字段)
}
自动生成的 Java 代码将为 sample
生成一个名为 SampleCase
的枚举,其中包含
enum SampleCase {
STR(1)
I(2)
...
}
现在在应用程序方面,我希望根据枚举 SampleCase
的类型在不同的对象上调用方法。一种简单的方法是使用 if-else:
if(case == SampleCase.STR) {
obj1.call();
} else if(case == SampleCase.I) {
obj2.call();
} else if(....)
...
访问者模式似乎适用于避免 if-else。我查看了这个链接,但那需要修改枚举,而我无法修改生成的 protobuf 枚举。有没有其他方法来进一步处理?
另外,我也可以接受其他能解决这个问题的设计模式。
英文:
Let's say I have a proto object as follows:
oneof sample {
string str = 1;
int64 i = 2;
... (many other fields inside oneof)
}
The autogenerated java code will generate enum for sample
named SampleCase
which contains
enum SampleCase {
STR(1)
I(2)
...
}
Now on the application side, I want to call methods on different objects based on the type of enum SampleCase
. A naive way is to do if-else:
if(case == SampleCase.STR) {
obj1.call();
} else if(case == SampleCase.I) {
obj2.call();
} else if(....)
...
Visitor pattern seems a good fit here to avoid if-else. I looked at this, but that would require modifying the enums and I don't have access to modify the protobuf generated enums. Any approach how to proceed further?
Also I am open to any other design patterns that could solve this issue.
答案1
得分: 1
一个避免在代码中多处出现“我在很多地方都有这些if-else”的方法是创建自己的领域对象并实现访问者模式。
你可以在接收到Proto生成的对象时,在一个地方将其转换为领域对象,之后你可以在其他任何地方都使用访问者模式,而不是使用switch语句/if-else语句。
无论如何,你仍然需要依赖switch/if-else语句,但这将集中在一个转换的地方,而不是遍布整个代码。
这也将使你能够将所有东西与Proto类分离开来。
英文:
One option to avoid having, quoting you, "I have this if-else's in many places in my code". Is to create your own domain objects that implement the Visitor pattern.
You convert the Proto generated objects to the domain object in one place right when you receive them, and after that you can use visitor pattern everywhere else instead of the switch cases / if-else.
You will have to depend on a switch / if-else case anyway, but that will be centralized in one place of conversion, instead of all over the code.
This will also enable you to decouple all your from the proto classes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论