At the risk of greatly over-engineering I actually suggest state-pattern. Essentially you have a State
abstraction:
interface State extends Runnable {}
with two implementations:
class FirstState extends State {
public void run() {
//[block of code]
state = new SecondState();
}
}
class SecondState extends State {
public void run() {
//[block instructions]
}
}
The FirstState
switches current state
:
private State state = new FirstState();
Your method()
now has no conditional logic:
public void method()
{
state.run();
}
However in 99% of cases boolean
flag is enough...
UPDATE: the solution above is not thread-safe. If you need it, simple AtomicReference<State> state
won't will be enough (see Marko Topolnik comment below) or you need to synchronize the whole method()
:
public synchronized void method()
{
state.run();
}