我正在阅读 Orielly 设计模式,其中有一行“我们可以更改
运行时的任何对象
”以及如何使用 getter 和 setter 在运行时更改对象的行为。
最佳答案
行为是对象的工作方式。运行时间就是应用程序的生命周期。因此,该语句意味着在程序运行期间我们能够操纵对象可以执行的操作。
要模拟,请参阅以下示例:
public class MyObjectTest {
public static final void main(String[] args) {
MyObject myObject = new MyObject();
String theMessage = "No message yet.";
theMessage = myObject.readSecretMessage();
myObject.setIsSafe(true);
theMessage = myObject.readSecretMessage();
}
}
public class MyObject {
private boolean isSafe = false;
public boolean isSafe() {
return this.isSafe;
}
public boolean setIsSafe(boolean isSafe) {
return this.isSafe = isSafe;
}
public String readSecretMessage() {
if(isSafe()) {
return "We are safe, so we can share the secret";
}
return "They is no secret message here.";
}
}
分析:
程序将返回两条不同的消息,决定取决于字段isSafe
。可以在运行时的对象生命周期(对象生命周期以运算符 new
开始)期间进行修改。
这意味着我们可以改变对象的行为。
关于java - "we change behavior of any object at runtime in java"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15759932/