多态性与封装. [英] Polymorphism Vs. Encapsulation.

查看:72
本文介绍了多态性与封装.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Command对象层次结构,该对象被序列化,然后在连接的两侧进行反序列化(手动),我为每个Inherited对象分配一个不同的枚举值(以不同的方式初始化抽象Command. .),这样我就能知道我收到了什么.
无论如何...现在我正在处理命令的多态句柄.我可以编写一个称为"Handle"的虚拟方法,其他每个Command的操作方式都不同,但是随后我必须提供一些资源,例如数据库连接,以及向发送者发送响应的功能,这当然会严重违反了OOP的封装概念.另一方面,我当前的设计在enum值上使用switch语句,并运行解释器级别的handle方法,可以与Socket模块和Database模块进行通信.

哪一种设计更好?
A.虚拟句柄方法-可能是更漂亮的多态代码,但是需要提供对Socket和Database模块的访问权限-封装不好.
B.糟糕的switch语句-半多态代码... Visual Studio Code Metrics似乎并不喜欢它(可维护性<60,将来还会增加更多情况...),但是封装被保留...

也许我缺少一个调整项?你们会推荐什么?

I have a Command object-hierarchy that is being serialized and then deserialized (manually) in two sides of a connection, I''m assigning every Inherited object a different enum value (initializes the abstract Command in a different manner...) so I can know what I''m receiving.
Anyway... Now I''m working on a polymorphic handle of a command. I could just write a virtual method called "Handle", and every other Command would operate differently, but then I would have to supply some resources, like database connection, and the functionality to send a response to the sender, and that would of course be a major breach of encapsulation concept of OOP. On the other hand, My current design uses a switch statement on the enum value, and operates a handle method which is on the interpreter level, can talk to the Socket module, and the Database module.

Which one of the designs is better?
A. Virtual Handle method - possibly prettier polymorphic code, but with the need to provide access to the Socket and Database modules - bad encapsulation.
B. Ugly switch statement - semi-polymorphic code... Visual Studio Code Metrics doesn''t seem to be very fond of it (<60 in maintainability and more cases will be added in the future...), but encapsulation is preserved...

Maybe there''s a tweak that I''m missing? What would you guys recommend?

推荐答案

只需使用我的 fastJSON [ ^ ]代码进行序列化并反序列化,您将不需要任何枚举或switch语句,因为您将在另一端获得确切的对象.
Just use my fastJSON[^] code to serialize and deserialize, you won''t need any kind of enum or switch statement as you will get the exact object at the other end.


我想我会选择丑陋的开关"声明,也许创建DSL和代码生成器以简化维护. xml,甚至包含枚举的程序集,也可以用作小型代码生成工具的输入.

最好的问候
Espen Harlinn
I think I would go for the "Ugly switch" statement, perhaps creating a DSL and a code generator to ease maintenance. xml, or even the assembly containing the enum, could also serve as the input to a small code generation tool.

Best regards
Espen Harlinn


这篇关于多态性与封装.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆