繁体   English   中英

Java处理许多具体工厂

[英]Java dealing with a lot of concrete factories

我想为很多(〜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与Factory Method重构一起使用,但是它没有帮助。

由于CMFactory几乎是一个功能接口,因此可以使用构造函数句柄,而不是为每个具体类实现CMFactory

使CMFactory接口:

public interface CMFactory<E extends CMObject, F extends IndexedFile<E>> {
    public abstract F makeFile(ByteBuffer[] buff);
}

然后写

public CityFile getCities() {
    return indexFile(CityFile::new);
}

您甚至可以丢弃CMFactory并使用java.util.Function

public <E extends CMObject, F extends IndexedFile<E>> F indexFile(Function<ByteBuffer[],F> factory) {
    ByteBuffer[] buffs;
    // ...filling buffers...
    return factory.apply(buffs);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM