gpt4 book ai didi

java - 使用实现一对接口(interface)的成对类

转载 作者:行者123 更新时间:2023-12-01 10:01:51 25 4
gpt4 key购买 nike

我有两个类,FooBar,以及一个使用这两个类的 Algorithm 类。

class Foo {
void method(Bar bar) {
bar.otherMethod();
...
}
}

class Bar {
void method() {
...
}

void otherMethod() {
...
}
}

class Algorithm {
void run(Foo foo, Bar bar) {
foo.method(bar);
bar.method();
...
}
}

算法部分(run方法)是通用的,我希望能够在其他项目中重用它,涉及类似于Foo和<的其他类对code>Bar,我知道每个都有名为 method 的方法。但是,我不想将 Bar.otherMethod 放在接口(interface)级别(因为它不是其他 IFooIBar< 所需的通用功能)/code> 对)。



为此,我定义了两个接口(interface):



interface IFoo {
void method(IBar bar);
}

interface IBar {
void method();
}

为了使用这些接口(interface),将Algorithm.run()的签名更改为

void run(IFoo foo, IBar bar).

问题是,现在,在 Foo 类中,我必须进行强制转换才能使用其关联的 Bar 类中的特定方面。当我使用另一对类时,可能必须进行类似的转换(例如,我可能有 Foo2Bar2,其中 Foo2.method 我需要将其 IBar 参数转换为 Bar2,以便能够使用特定功能)。

class Foo implements IFoo {
void method(IBar bar) {
(Bar)bar.otherMethod();
...
}
}

一般来说,这种 Actor 阵容是糟糕设计的标志。确实有问题吗?对于我想要拥有通用 Algorithm.run() 方法的意图来说,什么是更好的方法?

编辑:一个相关的方面是,FooBar 实现在实践中实际上是成对出现的。在某些时候,我可能有其他类,Foo2Bar2,其中Foo2.method不需要调用Bar2.otherMethod。在这种情况下,最初的 Foo 将与 Bar2 不兼容,但我对此类用例不感兴趣 - 这是否可以通过不同的设计来标记?

Edit2:更改了标题和文本,以更好地表达我有兴趣一次使用一对 FooBar 类。

最佳答案

您可能想利用泛型。也许你有:

interface Bar {
void frob();
}

interface Foo<T extends Bar> {
void frood(T bar);
}

然后当你写:

Foo<SomeBar> foo = // ...
SomeBar bar = // ...
foo.frood(bar);

Foo 实现知道它不只是任何 Bar,而是一个 SomeBar

关于java - 使用实现一对接口(interface)的成对类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750422/

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