【发布时间】:2015-11-02 10:43:20
【问题描述】:
请注意更新,我的问题没有明确表述。很抱歉。
假设我们有以下代码:
class Foo extends/implements AnAbstractClass/AnInterface { /* to make sure the constructor with int as input is implemented */
Foo(int magicInt) { magicInt + 1; /* do some fancy calculations */ }
}
class Bar extends/implements AnAbstractClass/AnInterface { /* to make sure the constructor with int as input is implemented */
Bar(int magicInt) { magicInt + 2; /* do some fancy calculations */ }
}
class Factory<T extends/implements AnAbstractClass/AnInterface> {
int magicInt = 0;
T createNewObject() {
return new T(magicInt) // obviously, this is not working (*), see below
}
}
/* how it should work */
Factory<Foo> factory = new Factory<Foo>();
factory.createNewObject() // => Foo with magicInt = 1
Factory<Bar> factory = new Factory<Bar>();
factory.createNewObject() // => Bar with magicInt = 2
在(*)位置我不知道该怎么办。我怎样才能确保具有这样签名的构造函数 ...(int magicInt) 已实现?我无法定义
-
接口中具有特定签名的构造函数
interface AnInterface { AnInterface(int magicInt); } -
一个执行特定构造函数的抽象类
abstract class AnAbstractClass { abstract AnAbstractClass(int magicInt); }这显然缺少在子类中实现构造函数的要求:
abstract class AnAbstractClass { AnAbstractClass(int magicInt) {} } an interface 或 abstract class 中的静态方法,可以为
AnInterface或AnAbstractClass的每个实现重写(我想到了工厂模式)
要走的路是什么?
【问题讨论】:
-
我认为你想要的结果代码有些奇怪。
SampleSource具有扩展SampleFactory的参数。然后在getCurrentSample()中调用这个样本工厂来创建一个应该与SampleFactory具有相同类型的样本。那么创建一个样本会给你一个样本工厂吗? -
好吧,因为接口中允许使用 Java 8 静态方法。
-
拥有扩展
Sample并实现SampleFactory的类似乎很奇怪... -
@Flown 他不想在接口中使用静态方法,他希望使用接口来强制实现该接口的类有一个。
-
由于类型擦除,
T的实际类型在运行时是未知的,所以T.class将不起作用。
标签: java generics constructor factory-pattern static-constructor