gpt4 book ai didi

java - 方法链接 : How to use getThis() trick in case of multi level inheritance

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:26 24 4
gpt4 key购买 nike

我的问题是关于 Method chaining + inheritance don’t play well together? 的.但不幸的是,方法链接的所有示例/答案都使用单级继承。我的用例涉及多级继承,例如

abstract class PetBuilder{...}
class DogBuilder extends PetBuilder{..}
class DogType1Builder extends DogBuilder {...}

要构建 Dog 对象,我将使用 DogBuilder 或 DogType1Builder

如何在上述用例中使用 getThis 技巧?

我想使用构建器模式来构造一个复杂的 Dog 对象(Dog 对象模型)"。DogType1 将添加一些属性。

所以使用getThis Trick 上面类的声明会变成这样

abstract class PetBuilder<T extends PetBuilder<T>>
class DogBuilder<T extends DogBuilder<T>> extends PetBuilder<DogBuilder<T>>
class DogType1Builder extends DogBuilder<DogType1Builder>

现在这会产生两个问题

1.'DogBuilder' 中的 builder 方法看起来像

public T someMethodInDog(String dogName) {
..
return (T)this; ///i dont want type casting and i cant use getThis Trick Here (compiler reports error for conversion from DogBuilder to T)
}

2.由于 DogBuilder 已参数化,因此要创建“DogBuilder”实例,我将不得不使用

DogBuilder<DogBuilder> builder=new DogBuilder(); //passing <DogBuilder> type ...real pain

有没有更好的方法?

最佳答案

你的问题的根源是类设计问题:你试图从一个具体的类继承,这几乎总是一个错误,并且(你的例子)势必会导致无数问题。为了坚持引用线程中给出的示例,您不应该实例化 Dog,因为在这样的宇宙中一般不存在 DogPet - 仅 PoodleNewFoundlandSpaniel 等。因此,getThis 不应在中级(抽象)类中实现,而应仅在(具体)叶类中实现。并且在所有的中级抽象类中,你应该只引用泛型类型参数T,而不是实际的类名。

这是 the answer to the referred thread 中的示例按照以上规则改写:

public class TestClass {

static abstract class Pet <T extends Pet<T>> {
private String name;

protected abstract T getThis();

public T setName(String name) {
this.name = name;
return getThis(); }
}

static class Cat extends Pet<Cat> {
@Override protected Cat getThis() { return this; }

public Cat catchMice() {
System.out.println("I caught a mouse!");
return getThis();
}
}

// Dog is abstract - only concrete dog breeds can be instantiated
static abstract class Dog<T extends Dog<T>> extends Pet<T> {
// getThis is not implemented here - only in concrete subclasses

// Return the concrete dog breed, not Dog in general
public T catchFrisbee() {
System.out.println("I caught a frisbee!");
return getThis();
}
}

static class Poodle extends Dog<Poodle> {
@Override protected Poodle getThis() { return this; }

public Poodle sleep() {
System.out.println("I am sleeping!");
return getThis();
}
}

static class NewFoundland extends Dog<NewFoundland> {
@Override protected NewFoundland getThis() { return this; }

public NewFoundland swim() {
System.out.println("I am swimming!");
return getThis();
}
}

public static void main(String[] args) {
Cat c = new Cat();
c.setName("Morris").catchMice();
Poodle d = new Poodle();
d.setName("Snoopy").catchFrisbee().sleep();
NewFoundland f = new NewFoundland();
f.setName("Snoopy").swim().catchFrisbee();
}
}

关于java - 方法链接 : How to use getThis() trick in case of multi level inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9655335/

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