简体   繁体   English

使用getter访问静态对象,“公共静态”或“私有静态”的最佳实践

[英]Best practice to access static object, 'public static' or 'private static' with getter

I have a class Foo which contain a static Map<String, String> myMap and some public static methods which manipulate myMap . 我有一个Foo类,其中包含一个static Map<String, String> myMap和一些操作myMap public static方法。

myMap is common Map("common content") for some classes in my project. myMap是项目中某些类的通用Map(“通用内容”)。

Those classes, which need myMap , only read data from it and always change data from myMap using methods from Foo . 这些需要myMapmyMap其中读取数据,并始终使用Foo方法更改myMap数据。

My question is: How is the best practice to declare and access myMap , in my case? 我的问题是:在我的情况下,最佳实践是如何声明和访问myMap As public static and access like Foo.myMap or as private static and acces like Foo.getMyMap() which will return a copy of myMap ( new HashMap<String, String>(myMap) ). 作为public static Foo.myMap和访问权(如Foo.myMap或作为private static Foo.myMap和访问Foo.getMyMap()Foo.getMyMap() ,这将返回myMap的副本( new HashMap<String, String>(myMap) )。 Or this depends only by my preferences? 还是这仅取决于我的喜好?

Follow these steps in the following order: 请按照以下顺序执行以下步骤:

  1. Try to avoid static in general, because it is not in regards to OOP principles. 尽量避免使用static ,因为它与OOP原则无关。
  2. If you insist to use static , the field must be final regardless of the access way usage. 如果您坚持使用static ,则该字段必须是final而不管访问方式的使用情况如何。
  3. Prefer getters over public visibility modifier. 相对于public可见性修饰符,更喜欢使用getters剂。

But yes, it depends always to your preferences. 但是,是的,这始终取决于您的偏好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM