重复此java代码重复

ter*_*hau 5 java code-duplication deduplication

我有大约10个类,每个类都有一个LUMP_INDEX和SIZE静态常量.我想要一个这些类的数组,其中数组的大小是使用这两个常量计算的.目前我有一个函数为每个类创建数组,有些内容如下:

private Plane[] readPlanes()
{
    int count = header.lumps[Plane.LUMP_INDEX].filelen / Plane.SIZE;
    Plane[] planes = new Plane[count];
    for(int i = 0; i < count; i++)
        planes[i] = new Plane();

    return planes;
}

private Node[] readNodes()
{
    int count = header.lumps[Node.LUMP_INDEX].filelen / Node.SIZE;
    Node[] nodes = new Node[count];
    for(int i = 0; i < count; i++)
        nodes[i] = new Node();

    return nodes;
}

private Leaf[] readLeaves()
{
    int count = header.lumps[Leaf.LUMP_INDEX].filelen / Leaf.SIZE;
    Leaf[] leaves = new Leaf[count];
    for(int i = 0; i < count; i++)
        leaves[i] = new Leaf();

    return leaves;
}
Run Code Online (Sandbox Code Playgroud)

这些函数中有10个,唯一的区别是类类型,所以你可以看到,有很多重复.

有没有人对如何避免这种重复有任何想法?谢谢.(之前我问了一个类似的问题,但我想我问的方式有点过时了)

Bri*_*ach 1

好吧,多克......我已经对此进行了测试以确保,并且我相信它可以满足您的要求。

你需要一个接口:

public interface MyInterface
{
    public int getSize();
    public int getLumpIndex();
}
Run Code Online (Sandbox Code Playgroud)

您的类实现该接口:

public class Plane implements MyInterface
{

    ...
    public int getSize()
    {
        return SIZE;
    }

    public int getLumpIndex()
    {
        return LUMP_INDEX;
    }

}
Run Code Online (Sandbox Code Playgroud)

header在作为实例的类中,您有......

public <E extends MyInterface> E[] 
    getArray(Class<E> c, MyInterface foo)
{
    int count = lumps[foo.getLumpIndex()].filelen / foo.getSize();
    E[] myArray = (E[]) Array.newInstance(c, count);
    for(int i = 0; i < count; i++)
         myArray[i] = c.newInstance();
    return myArray;
}
Run Code Online (Sandbox Code Playgroud)

你可以从你的 Plane 类中调用它:

Plane[] p = header.getArray(Plane.class, this);
Run Code Online (Sandbox Code Playgroud)

认为?:) 有人可以看看这个并看看我是否离开了吗?

编辑:因为我现在已经测试过它 - 有效)

另外,您可以通过getArray()将大小和索引作为参数来消除每个类中的吸气剂:

public <E extends MyInterface> E[] 
    getArray(Class<E> c, int size, int index)
{
    int count = lumps[index].filelen / size;
    E[] myArray = (E[]) Array.newInstance(c, count);
    for(int i = 0; i < count; i++)
         myArray[i] = c.newInstance();
    return myArray;
}
Run Code Online (Sandbox Code Playgroud)

并将其称为:

Plane p[] = header.getArray(Plane.class, SIZE, LUMP_INDEX);
Run Code Online (Sandbox Code Playgroud)

从你的班级内部。接口只是变空以提供泛型类型,并且您不必定义 getter 方法。

或者(我保证最后一次编辑,但这确实给了你选择并解释了一些关于泛型的信息)

抛弃接口。这删除了一些健全性检查,因为该方法不关心您给它什么类型的对象:

public <E> E[] 
    getArray(Class<E> c, int size, int index)
{
    ...
Run Code Online (Sandbox Code Playgroud)

现在您不必定义接口或实现它,您只需调用:

Plane p[] = header.getArray(Plane.class, SIZE, LUMP_INDEX);
Run Code Online (Sandbox Code Playgroud)