【发布时间】:2016-06-21 12:04:40
【问题描述】:
我想为许多(约 40-50)个相似实体概括一段重复的 Java 代码(在我的例子中,这段代码是对具有这些实体的文件的索引)。
我尝试使用泛型方法对其进行重构,但结果是,我得到了一个泛型类的构造函数,这在 Java 中显然是被禁止的。为了避免这种情况,我实现了抽象工厂模式,这就是我得到的。
public <E extends CMObject, F extends IndexedFile<E>> F indexFile(CMFactory<E, F> factory) {
F items;
ByteBuffer[] buffs;
// ...filling buffers...
items = factory.makeFile(buffs); // as I cannot do items = new F(buffs)
return items;
}
public CityFile getCities() {
return indexFile(new CityFactory());
}
public ContinentFile getContinents() {
return indexFile(new ContinentFactory());
}
// a lot of more
这解决了创建泛型类实例的问题。然而,我现在面临的任务是为每个实体创建一个具体的工厂,这似乎是很多单调的工作,因为它们看起来都彼此相似。
public abstract class CMFactory<E extends CMObject, F extends IndexedFile<E>> {
public abstract F makeFile(ByteBuffer[] buff);
}
public class CityFactory extends CMFactory<City, CityFile> {
@Override
public CityFile makeFile(ByteBuffer[] buff) {
return new CityFile(buff);
}
}
public class ContinentFactory extends CMFactory<Continent, ContinentFile> {
@Override
public ContinentFile makeFile(ByteBuffer[] buffs) {
return new ContinentFile(buffs);
}
}
问题是:有没有办法自动创建这样的工厂?或者也许有另一种模式至少可以让这种创作不那么痛苦?
我尝试使用 IntelliJ IDEA 的 Replace Constructor with Factory Method 重构,但它没有帮助我。
【问题讨论】:
标签: java generics intellij-idea abstract-factory