Class variable: read-only public access but r / w private access

In my current project, I have a class that stores its instance in a variable. This instance should be accessible to all other classes of the project, but it can only be modified by its own class.

How can i achieve this?

+4
source share
4 answers

Write a set of public getter, but not public . And the private field itself

+18
source

In short, this is called an immutable object ; the state of an Object cannot change after it is created.

String is a common example of the immutable Class .

Make Class immutable as follows:

  • make sure the class cannot be overridden - make Class final , or use static and keep the constructors private.
  • enter the private and final fields
  • force callers to completely construct the object in one step, instead of using the no-argument constructor in combination with the next, calls the setXXX methods.
  • they do not provide any methods that can change the state of an object in any case - not only setXXX methods, but also any method that can change state
  • If the class has any modifiable fields of the object, then they must be securely copied during transmission between the class and its caller.
+4
source

Someone offers a "public getter, but not a public setter for a private field."

Note: this will only work if the field is a primitive type.
If it is an object with setters, the content can still be changed; therefore, not read-only.

It will be interesting to see that the Java language provides some constructs to make the return type read-only, without having to make a deep copy / clone.

I look like ReadOnly getEmployee () {...}

+2
source

The template code for creating an instance of a singleton object can be found in many places, for example, http://www.javacoffeebreak.com/articles/designpatterns/index.html

Keep in mind that many people think that singleton is antipattern because it’s pretty hard to get rid of how your application is dotted with links to singleton.

0
source

All Articles