问题
In my current project I have a class which stores its Instance in a variable. This Instance should be accesible by all other classes in the project, but it may only be altered by its own class.
How can I achieve this?
回答1:
Write a public getter but no public setter. And the field itself private
回答2:
In short that is called immutable object, state of Object cannot change after it is constructed.
String is a common example of immutable Class.
Make a class immutable by following-
- ensure the class cannot be
overridden- make theclassfinal, or usestaticfactories and keep constructors private. - make fields
privateandfinal - force callers to construct an object completely in a single step,
instead of using a
no-argument constructorcombined with subsequent calls tosetXXXmethods. - do not provide any methods which can change the state of the object
in any way - not just
setXXXmethods, but any method which can change state - if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller.
回答3:
Someone suggests "public getter but no public setter for the private field."
Caution: This would only work if the field is primitive type.
If it is an object with setters, the content can still be modified; thus not read-only.
It will be interesting to see Java language provide some constructs to make a return type read-only without having to do a deep-copy / clone.
i'm imaging like ReadOnly getEmployee() { ...}
回答4:
The boilerplate code for instantiating a singleton can be found in many places, see for example http://www.javacoffeebreak.com/articles/designpatterns/index.html
Be aware that many consider the singleton to be an antipattern because it's pretty hard to get rid of once your application is littered with references to the singleton.
来源:https://stackoverflow.com/questions/14324805/class-variable-public-access-read-only-but-private-access-r-w