我想实现一个在第一次调用时具有不同行为的方法,然后在第二次调用它时。
怎么做?
答案 0 :(得分:5)
Java中的实例方法可以访问类的状态。添加一个变量来指示之前是否已调用过这些方法,并使用它来决定在方法内部采用的两条路径:
class FirstTimeCaller {
private boolean isFirstTime = true;
void methodWithState() {
if (isFirstTime) {
... // Do first-time thing
isFirstTime = false;
} else {
... // Do the other thing
}
}
}
这适用于同一对象的方法:第一次调用将在您第一次在methodWithState
类的每个新对象上调用FirstTimeCaller
时执行。
如果您希望为静态方法实现相同的行为,或者您希望在任何实例上进行第一次调用以执行其他操作,并且所有后续调用都要执行其他操作,使isFirstTime
字段static
。
答案 1 :(得分:2)
您只需创建一个变量
即可int counter = 0; // This means the method has not been called yet
当调用该方法时,只需在其中执行此代码:
counter++; // Increment by 1 for each new call
并且您有一些存储在变量“counter”中的方法调用,因此您可以选择如何处理它。
答案 2 :(得分:2)
只是为了扩展可能的解决方案列表,您也可以考虑State-Pattern:
public class Sandbox {
private Runnable delegate = () -> {
System.out.println("First Time");
delegate = () -> System.out.println("Second Time");
};
public synchronized void doIt() {
delegate.run();
}
}
答案 3 :(得分:1)
public class MethodLogic implements Callable<String> {
private boolean called = false;
public String call() {
if (!called) {
called = true;
return "first";
} else {
return "not first";
}
}
}
稍后使用它
Callable<String> method = new MethodLogic();
System.out.println(method.call());
System.out.println(method.call());
答案 4 :(得分:1)
如果在多线程上下文中调用,则需要注意并发访问。例如,您可以使用AtomicBoolean:
public class FirstAndSecondTime {
private static final AtomicBoolean FIRST_TIME = new AtomicBoolean(true);
public void perform() {
if (FIRST_TIME.compareAndSet(true, false)) {
//execute first time logic here
} else {
//execute 2-n time logic here
}
}
}
答案 5 :(得分:1)
使用静态类:
public class MyStaticClass {
private static boolean firstTime = true;
public static void myMethod() {
if (firstTime) {
System.out.println("First time");
} else {
firstTime = false;
System.out.println("NOT first time");
}
}
}
然后你会像这样使用它:
MyStaticClass.myMethod(); //-> prints "First time"
MyStaticClass.myMethod(); //-> prints "NOT first time"
MyStaticClass.myMethod(); //-> prints "NOT first time"
这是Singleton设计模式在延迟初始化时的作用:
public final class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
if (instance == null) {
instance = new Singleton();
}
}
return instance;
}
}
您可能不应该使用此功能(除非您将它用于Singleton,我猜),但在对象上使用字段:
public class MyMessagePrinter {
private int counter = 0;
public void printMessage() {
if (this.counter > 0) {
System.out.println("Fist time");
} else {
System.out.println("NOT first time");
}
}
}
像这样使用它:
MyMessagePrinter myPrinter = new MyMessagePrinter();
myPrinter.print(); //-> prints "First time"
myPrinter.print(); //-> prints "NOT first time"
myPrinter.print(); //-> prints "NOT first time"
请注意代码不是thread safe