"我们在java中改变运行时任何对象的行为"是什么意思

Tus*_*har 2 java runtime

我正在阅读Orielly Design模式,并且有一行" We can change the Behavior of any object at runtime"以及如何使用getter和setter在运行时更改对象的行为.

Dam*_*ash 6

行为是对象的工作方式.运行时间是应用程序的寿命.所以这个陈述意味着在程序运行期间我们能够操纵对象可以做什么.

要模拟它,请参阅以下示例:

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.";
 }
}
Run Code Online (Sandbox Code Playgroud)

分析:

该程序将返回两个不同的消息,决定取决于字段isSafe.这可以new在运行时对象生命期间(使用运算符的对象生命开始)进行修改.

这意味着我们可以改变对象的行为.