gpt4 book ai didi

在构造函数中使用 "this"的 Java 双向对象引用

转载 作者:行者123 更新时间:2023-11-30 01:50:59 25 4
gpt4 key购买 nike

我正在尝试创建对象和组件对象,它们之间具有双向引用。在此示例中,我有一个 Bike 类和一个 Wheel 类。我考虑的一个选项(选项 1)是让 Bike 创建 Wheel,然后在其构造函数中将自身引用传递给 Wheel。但是,我读到我不应该在构造函数之外传递“this”,并且最好在 Bike 构造函数之外创建 Wheel 对象。所以我应该先创建 Wheel,然后将其传递给 Bike,然后调用 Wheel 的 setBike() 方法(选项 2)。在我看来,选项 1 是在 Bike 和 Wheel 之间创建双向引用的最简单方法,但它似乎也违反了一些设计原则。有人可以解释为什么选项 2 比选项 1 更好吗?

选项 1:

public class Wheel {

private Bike bike;

Wheel(Bike bike) {
this.bike = bike;
}
}

public class Bike {

private Wheel wheel;

Bike() {
this.wheel = new Wheel(this);
}
}

Bike bike = new Bike();

选项 2:

public class Wheel {

private Bike bike;

public void setBike(Bike bike) {
this.bike = bike;
}
}

public class Bike {

private Wheel wheel;

Bike(Wheel wheel) {
this.wheel = wheel;
}
}

Wheel wheel = new Wheel();
Bike bike = new Bike(wheel);
wheel.setBike(bike);

最佳答案

第一个选项并不像您想象的那么理想。它不仅传递了 this 而对象没有完全初始化: this.wheel = new Wheel(this); 而在这里它不应该造成任何麻烦,因为这是一个非常简化了使用,但此选项也产生了一个设计问题:轮依赖项在构造函数中被硬编码。您无法切换/模拟依赖项实例。

一般来说,双向关系会产生一些约束,迫使您进行一些设计权衡:两次设置值,没有不变性,至少有一个暴露的 setter ,等等......请注意,您可以应对一些通过引入一些额外的抽象来解决这些问题。

但是为了简单起见,“单独”创建两个对象中的至少一个是正确的选择,如第二个选项所示。如果您在构造函数中处理相互关系,则可以节省 setter 部分调用:

Wheel wheel = new Wheel();
Bike bike = new Bike(wheel);
// wheel.setBike(bike); // not required now

其中自行车定义为:

Bike(Wheel wheel){
this.wheel = wheel;
wheel.setBike(this);
}
<小时/>

更进一步,如上所述,您可以通过引入一些抽象来减少两个类之间的耦合以及关联两个实例的方式。
例如,您可以引入自行车和车轮界面,这将是客户端操作自行车和车轮的唯一方式。通过这种方式,您可以使用客户端永远不会看到的内部实现来执行双向关系,甚至在幕后执行一定程度的不变性(感谢 private 嵌套 类)。
当您开发 API 时,这通常是确保某些不变量和规则的一种方法。

我们的想法是客户只需:

Bike bike = CarFactory.of("super bike", "hard wheel");
Wheel wheel = bike.getWheel();

接口(interface):

public interface Wheel {
String getBarProp();
Bike getBike();
}

public interface Bike {
String getFooProp();
Wheel getWheel();
}

以及客户端 API,而不是 CarFactory 中的公共(public)实现:

public class CarFactory {

private static class BikeDefaultImpl implements Bike {

private final String fooProp;
private Wheel wheel;

public BikeDefaultImpl(String fooProp) {
this.fooProp = fooProp;
}

@Override
public String getFooProp() {
return fooProp;
}

@Override
public Wheel getWheel() {
return wheel;
}
}


private static class WheelDefaultImpl implements Wheel {

private final String barProp;
private Bike bike;

public WheelDefaultImpl(String barProp) {
this.barProp = barProp;
}

@Override
public String getBarProp() {
return barProp;
}

@Override
public Bike getBike() {
return bike;
}
}


public static Bike of(String bikeProp, String wheelProp) {
BikeDefaultImpl bike = new BikeDefaultImpl(bikeProp);
WheelDefaultImpl wheel = new WheelDefaultImpl(wheelProp);
bike.wheel = wheel;
wheel.bike = bike;
return bike;
}

}

您还会注意到,这种方式不再需要构造函数中的 this 用法,因为我们可以在内部自由访问 Bike 和 Wheel 实现的字段。

关于在构造函数中使用 "this"的 Java 双向对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080664/

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