几何函数索引

Vin*_*arg 1 java indexing graphics swing hashmap

我正在制作一种基于命令的应用程序来绘制几何图形.因此,如果用户输入的内容类似于RECT 100, 50, 200, 120我在绘图面板上的指定位置绘制矩形.

所以对于这个我需要映射RECTg.drawRect(100, 50, 200, 120);和所有这些类似的功能来绘制几何图形.

我将使用哈希映射进行映射,但我不知道如何在java中构建函数数组.在C++中,我已经做到了这一点.

键可以是'RECT',值可以是索引的偏移量.

请告诉我如何索引这些功能.或者还有更好的方法来解决主要问题吗?

das*_*ght 5

Java中没有函数指针,您需要通过继承和/或接口来完成.这是一个例子:

interface Shape {
    void draw(int[] data);
}

class Polygon implements Shape {
    public void draw(int[] data) {
        // Draw polygon using points data[i], data[i+1] for points
    }
}

class Circle implements Shape {
     public void draw(int[] data) {
         // Draw circle using data[0], data[1] for the center, and data[2] for radius
     }
}
Run Code Online (Sandbox Code Playgroud)

在主程序的构造函数或静态初始化程序中:

Map<String,Shape> shapes = new HashMap<String,Shape>();
shapes.put("POLY", new Polygon());
shapes.put("CIRC", new Circle());
Run Code Online (Sandbox Code Playgroud)

在您的绘图代码中:

shapes.get("CIRC").draw(new int[] {100, 100, 50});
Run Code Online (Sandbox Code Playgroud)