gpt4 book ai didi

java - 当另一个类更新对象值时更新对象值

转载 作者:行者123 更新时间:2023-11-30 05:39:52 24 4
gpt4 key购买 nike

我有 3 节课。

Car.java
Garage.java
Driver.java
Race.java

所以我现在的情况是,我目前有 3 个独立的类,它们正在互相查找和更新。情况是当 Garage 更新 Car 属性时。每辆汽车还分配有司机。如果 Cars 属性已更改,我如何才能运行 acknoweldgeNewTires()

我尝试过 Observer 和 Observable,但显然它已被弃用,所以我正在寻找替代方案。

我当前的代码在这里:

Race.java

public class Race {

public static void main(String[] args){

Garage teamBlue = new Garage();
Car blueCar = new Car();
teamBlue.changeTires("Michelin");

}
}

Garage.java

public class Garage {

Car car;

public void changeTires(String tire){
Car.tiresBrand = tire;
}
}

Car.java

public class Car {

public static String tiresBrand = "Dunlop";
public Driver driver;

public Car(){

driver = new Driver(this);
}
}

驱动程序.java

public class Driver {

public Car driversCar;

public Driver(Car car){
driversCar = car;
}

public void acknoweldgeNewTires(){
System.out.println("New tires received!");
}
}

最佳答案

1) 不要在Car中使用static。轮胎是汽车用的,不是任何汽车的。
2) 要“拦截”此类事件,在更新 Car 状态时,您应该优先使用方法而不是 public 字段访问。

您可以使用发布者/订阅者模式来减少类之间的耦合,但这似乎是一种开销。

所以在 Garage 中你可以这样做:

private Car car;
private List<Car> cars; // Or better because a single Car for a Garage is weird
public void changeTires(String tire){
car.setTiresBrandAndNotifyDriver(tire);
}

在车里:

public void setTiresBrandAndNotifyDriver(String tire){
this.tire = tire;
this.driver.acknoweldgeNewTires();
}

关于java - 当另一个类更新对象值时更新对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com