dqbr37828 2017-02-07 17:06
浏览 56
已采纳

在类上创建静态工厂方法是否可以接受? [关闭]

I have a class whose instances are an object representing messages in a standardized format. These instances are eventually output as a JSON object so that they can be transferred between processes.

The class has some very helpful methods which I use to validate and control the message without delving into the object structure. This is fine and dandy when I'm creating the message and sending it out, but when I receive the JSON object it contains only data, and none of these helpful methods.

What is the best way to map these incoming JSON objects to a class instance?

I can think of four ways...

1) Add a static method to the class which accepts a JSON string and produces a new instance of the class.
2) Add a method to the class which accepts a JSON string and maps the JSON object to that instance.
3) Have an optional argument in the constructor which accepts a JSON string and maps it to the instance on construction.
4) Turn the class into a service with a factory method.

I would love to do 3, but the problem is that I cannot return feedback if the object wasn't correctly formatted, etc.

  • 写回答

1条回答 默认 最新

  • duandu1966 2017-02-07 17:18
    关注

    1) Add a static method to the class which accepts a JSON string and produces a new instance of the class.

    This will make the code harder to unit test and scale as features change. See unit testing and Static methods

    2) Add a method to the class which accepts a JSON string and maps the JSON object to that instance.

    This is a good idea. This could be useful in conjunction with #4. Implementing this alone might become tedious if you want to support multiple objects/JSON formats.

    3) Have an optional argument in the constructor which accepts a JSON string and maps it to the instance on construction.

    I personally find this to be an awkward use of the constructor. Things like JSON validation would need to throw an exception.

    4) Turn the class into a service with a factory method.

    Creating a factory is the most extensible way forward. Think down the line if you have multiple JSON formats and objects to map to. This central class would let you choose the correct mappings and handle changes over time. It's also easy to unit test.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了