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 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多