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

后端 未结 6 1771
后悔当初
后悔当初 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:06

    First of all, if you want to easy and quick way, use a simple boolean flag (just don't forget the concurrency issue and use @Marko Topolnik solution).

    But if we already opened a theoretical discussion and talked about design pattern, rather than using the state-pattern like @Tomasz Nurkiewicz mention, I would suggest to think of singleton (some will say it's more anti design pattern) and how to achieve only one instance of this class, so if requesting an instance of this class, the constructor will be called only in the first call.

    if you altentivly want more "outside the box" solution, you can use aop

提交回复
热议问题