【问题标题】:Java dealing with a lot of concrete factoriesJava 处理大量具体工厂
【发布时间】: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


    【解决方案1】:

    由于您的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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 2017-10-06
      • 2013-01-10
      • 2011-01-10
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多