有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的复合模式

我现在正在开发一个程序,它允许你创建形状(正方形、长方形和圆形)。你也可以通过选择已经创建的形状来创建复合形状。。。我用两个观察者观察这些形状。一个用于正方形/矩形,一个用于大圆,这些观察者列出了形状的参考点和大小。创建复合形状时,如果复合形状中有正方形/矩形,则应在正方形/矩形框中列出组件

我应该使用复合图案创建复合形状。基本上,我需要用同样的方法来处理正方形和正方形

我有一个叫做形状的对象数组,复合形状是一个包含形状数组的对象

我的问题是,如何在形状数组中检查复合形状类型的对象,然后在复合形状数组中检查矩形或正方形的实例

很抱歉没有包含代码,但我的程序有点大,有很多类

下面是我用来检查正方形或矩形实例的方法。。。这两种方法在两个不同的类中。当形状只是简单形状而复合形状不显示时,形状显示在右观察者窗口中。例如,如果我有一个包含3个形状的形状列表。。。形状1是一个大圆,形状2是一个复合形状,形状3是一个矩形。假设复合形状有两个正方形。现在,这将显示大圆和矩形,但不会显示复合形状组件。我想,一旦我到达compoundShape,instanceof将看起来像从compundshape数组中选择一个正方形或矩形的instanceof

这里是复合形状串法

public String toString(){
    String output="";
    output += "Compound Shape: /n";
    for (int i = 0; i< numShapes; i++){
        output += shapes[i].toString();
    }
    return output;
}

下面是我用来查找正方形或矩形实例的do方法

do {//squares rectangles
        currentShape = shapes.getShape();
        if (shapes.squareRectangleFinder())
            outputString1 += currentShape.toString();
    }while (shapes.next());

这是平方查找法

public boolean squareRectangleFinder() {
    if ((shapes[currentShape] instanceof Square)||(shapes[currentShape] instanceof Rectangle)){
        return true;
    }
    return false;
}

共 (1) 个答案

  1. # 1 楼答案

    我想这就是“复合模式”应该做的。根据Wikipedia

    clients should ignore the difference between compositions of objects and individual objects

    据我所知,应该这样做(getter/setter,add/remove操作省略):

    interface Shape {
        public int getLeftmostCoordinate();
    }
    
    class Rectangle implements Shape {
        private int top;
        private int left;
        private int width;
        private int height;
    
        public int getLeftmostCoordinate() {
            return left;
        }
    }
    
    class Circle implements Shape {
        private int x;
        private int y;
        private int r;
    
        public int getLeftmostCoordinate() {
            return x - r;
        }
    }
    
    class CompoundShape implements Shape {
        private Shape[] shapes;
    
        public int getLeftmostCoordinate() {
            int left = shapes[0].getLeftmostCoordinate();
    
            for (int i=1; i<shapes.length; i++) {
                int candidate = shapes[i].getLeftmostCoordinate();
                if (candidate < left) {
                    left = candidate;
                }
            }
    
            return left;
        }
    }