doulai2573 2014-05-19 21:25
浏览 72

用于存储全局常量,变量和辅助方法以在类之间共享的模式

I'm curious what patterns are being used to store constants and variables that are shared amongst classes. I'm trying to avoid passing around a container or utilizing a global helper file that's included at the root application. I suppose the constants could be declared in an interface and implemented by all of the components, but that doesn't address variables or methods. Extending a super class is out of the question.

Example: Let's say we're defining constants for common HTTP methods: HTTP_GET, HTTP_POST, etc. You want all components to ensure they are comparing to the same definition (e.g. 'Get' versus 'get' versus 'GET', etc.)

  • 写回答

1条回答 默认 最新

  • dtng25909 2014-05-20 14:34
    关注

    Shared constants can be defined as static variables but then the question to ask is which class should contain them? I've seen plenty of Contstants classes dedicated to this but these quickly degenerate into a jumbled mess. It's better to place them individually on the types which identify with them the most. For example, if you had a class called HttpRequest, then your request method constants would fit well there as HttpRequest.GET and HttpRequest.POST. If you don't have any one class that identifies with the constants more than others, at least create a class to group like constants such as HttpRequestMethods.POST and HttpRequestMethods.GET.

    If you have shared variables, be sure to encapsulate them with setProperty methods to make their modification thread safe since two or more collaborators could be modifying the variables at the same time. As for the class that contains them, instead of exposing the accessor methods statically, you may want to use the singleton pattern instead so that your shared variables are exposed on a shared object. That way you can use the benefit of OOP when the need arises. The singleton pattern can inhibit testability though so consider using an IOC container which will create one instance of this object an inject it into all collaborators that need access to these shared variables.

    评论

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?