I have an abstract class:
public abstract class AbstractCommand {
private static State state;
}
Intention
- An object of class
State
is provided by some "controlling classes", providing data that is needed by eachAbstractCommand
subclass - Each subclass needs read access to it
- The subclasses are not allowd to change the field
Current approach
The field state
should be initialized by the "controlling classes" of the program so that subclasses (that define commands) can use it (read-only). The subclasses are defined internally and should be used as an interface for the user. This user should not have write access to state
.
The problem
- Adding a public
setState()
method inAbstractCommand
would make it accessible to all subclasses and with that to the user - Making the field final would force the creating of the object to take place in the abstract class and the "controlling classes" would have to use this object, furthermore it would not be replacable
How do you handle something like this?
Another try
Because some answers suggested solutions using package visibility I wonder if this would do a good job:
Have a class in the same package that provides the required information by delegating a call from the "controlling classes" (from outside the package) to the abstract class.
Sounds a little fuzzy, too but what do you think?
state
variable to be "shared" among all of your commands? Seems to me you'd want to share state only among your extending classes (i.e. one for all instances of Command1, one for all instances of Command2, etc). – Solostate
asstatic
in your abstract class will cause all of your extending classes to share the same state. So if an instance ofCommand1
will have the same state as an instance ofCommand2
. Just making sure I understand what you want. – SologetState
method to these "controlling classes"? It seems to me like this is a bunch of extra work to achieve just that. – TranscendentalisticgetState()
in the conrolling classes... But when to call that? What if that object would change and another one has to be set? – Erupt@
, for example, @user905686, this sticks a notification in my inbox so I see your comment and can answer. Anyway, don't store it in a variable in your commands, just callgetState()
when you need it and store it in a local variable inside your method. Then you don't have to worry if it changes since you'll just be getting it when you need it. If you need to update commands when the state changes, you can use the observer pattern (a.k.a. "listeners" in Java). – Transcendentalistic