Reputation: 18123
Consider I have a interface like this:
public interface Test {
//Basically life cycle methods
public void beforeStart();
public void start();
public void end();
}
And there is a abstract class, which provides basic or empty implementations for all of the methods.
public abstract class TestAdapter implements Test {
//Implementations here
}
So that clients extending TestAdapter
, can override one, or all of the life cycle methods. I am mandating each consumer should extend TestAdapter
class and they can override all or one or none of the lifecycle methods in TestAdapter
.
But the problem is each consumer of TestAdapter
creates an instance of a POJO class for which life cycle should be managed ie beforeStart()
etc.
My question is:
testAdapter
implementation class. How can I proceed to implement this??Please let me know if you need more clarifications regarding same.
Edit: Note: If you feel I am trying to re-invent wheel, can you kindly suggest any alternative for above requirements?
Upvotes: 1
Views: 114
Reputation: 30528
First I think that you should use annotations as you can see in most test frameworks:
@BeforeClass
public void beforeClass() {
// code here
}
@BeforeMethod
public void beforeMethod() {
// code here
}
If you really want to stick with inheritance you can do something like this:
public abstract class TestAdapter implements Test {
private AbstractPojo myPojo;
protected void doBeforeStart(){
// do something which you always want to happen
beforeStart();
}
protected void doStart() {
start();
}
protected void doEnd() {
end();
}
// your empty implementations of Test here
// getter and setter for myPojo
}
In this case you can control internally what should happen and let your users override the methods in the interface as they see fit.
Upvotes: 1
Reputation: 17893
This problem is of "Creating an object step by step". This is solved by a Builder Pattern.
Here is another example in java for implementing Builder pattern.
Upvotes: 1
Reputation: 8230
You can have an argument in the method to control the POJO object.
On the other hand, there are a lot of ready frameworks to use instead of creating your own, why invent the wheel again?
Upvotes: 1