Re: a question related to "final static" field variable
www wrote:
I feel it is kind of silly that in order to get to know what the root
directory it is, Worker is forced to have a MyClass in it.
I think I see what you are trying to say. If I understand, you don't
like the fact that there is some dependency that the worker thread knows
about the MyClass class. I think one way to fix this is to use what is
sometimes called a Strategy Pattern or Dependency Injection. Rather
than have Worker know about MyClass, you inject the information into
Worker, thus breaking the dependency.
In plain English, I think Worker needs to know about the context in
which it's running, so let's call this dependency a "context"
public class Worker {
private Context localCntxt;
public Worker( Context c ) {
localCntxt = c;
}
public void doStuff() {
//...
String rootDir = localCntxt.getRootDir();
//...
}
}
Now just make MyClass a type of Context object:
public class Context { // used to be type MyClass
private String rootDir;
public void setRootDir( String s ) {
rootDir = s;
}
public String getRootDir() {
return rootDir;
}
}
Feel free to stuff Context full of every sort of variable that your
classes might ever need.
Now you can easily make lots of workers all running in the same context,
or even different contexts.
public class Main {
public void main( String [] args ) {
Context a = new Context();
Context b = new Context();
Context c = new Context();
a.setRootDir( "/" );
b.setRootDir( "/Users/Mark/pub" );
c.setRootDir( "/argle/bargle/blet/foo/bar" );
Worker w1 = new Worker( a ); // Three workers all
Worker w2 = new Worker( a ); // running in the same
Worker w3 = new Worker( a ); // Context
Worker w4 = new Worker( b ); // A Different Context b
Worker w5 = new Worker( c ); // And Context c
}
}
I hope this made some sense to you.