Call a block of a method only for the first call of the method

后端 未结 6 1786
后悔当初
后悔当初 2021-01-20 02:54

I have a method and inside this method I have a block:

public void method()
{
   [block instructions]
}

But this method is called twice in

6条回答
  •  半阙折子戏
    2021-01-20 03:04

    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 won't will be enough (see Marko Topolnik comment below) or you need to synchronize the whole method():

    public synchronized void method()
    {
        state.run();
    }
    

提交回复
热议问题