Reputation: 20565
I am creating several threads that will collect data from the database.
However in all of these threads i will need a local reference to my Database
object as far as i know there are two ways of doing this either i use an interface:
public interface Command {
void execute();
void collectData();
void processData();
void setData(ArrayList<Objects> data);
}
And then set the variable manually in each of the thead classes (that extends the command interface)
However doing my test and search i found that i could do the following:
public abstract class commandtest implements Runnable{
Database db;
abstract void execute();
abstract void collectData();
abstract void processData();
abstract void setData(ArrayList<Objects> data);
}
Here by have an abstract class that each of my thread objects can extend and then create a constructor to set the variables needed.
My question is rather simple which of these two methods is the best pratice?
Upvotes: 1
Views: 181
Reputation: 4877
Since you say that
in all of these threads i will need a local reference to my Database object
your second approach seems appropriate.
I would declare the db
variable as private since it is going to be different per thread (that is what i felt from your question). Else it could be mistaken to be shared across implementing classes.
private Database db;
and expose an abstract setDatabase(Database database)
method so each implementing class sets its database.
Upvotes: 1
Reputation: 727047
You should not decide on placement of variables based solely on the need to share some code or some variables. If your abstract class is designed with the idea that everything extending it must have access to Database
, then you put Database
in the base class.
On the other hand, if some of the intended implementations would have nothing to do with the database, then you should not add Database
to the abstract base class. Of course you are not limited to just two levels of the inheritance hierarchy: you can always start with commandtest
that does not have Database
, and add another level of abstract classes for everything that does need a database:
abstract class AbstractCommandTest {
abstract void execute();
abstract void collectData();
abstract void processData();
abstract void setData(ArrayList<Objects> data);
// Other methods shared by all commands
}
abstract class AbstractDatabaseCommandTest extends AbstractCommandTest {
protected Database db;
protected AbstractDatabaseCommandTest(Database db) {
this.db = db;
}
}
class SomeCommandThatDoesNotNeedDatabase extends AbstractCommandTest {
...
}
class DatabaseCommand1 extends AbstractDatabaseCommandTest {
...
}
class DatabaseCommand2 extends AbstractDatabaseCommandTest {
...
}
Upvotes: 2