java - java中的复合模式

标签 java composite

我现在正在开发一个程序,它允许您创建形状(正方形、矩形和圆形),您还可以选择通过选择已创建的形状来创建复合形状...我正在使用两个观察器来观察形状。一种用于正方形/矩形,一种用于大圆形,这些观察者列出了形状的引用点和尺寸。创建复合形状时,如果复合形状中有正方形/矩形,则应列出正方形/矩形框架中的组件。

我应该使用复合图案创建复合形状。所以基本上复合形状和我的圆形、正方形和矩形需要以相同的方式处理

我有一个称为形状的对象数组,复合形状是一个包含形状数组的对象。

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

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

这是我用来检查正方形或矩形实例的方法...这两种方法属于两个不同的类。当形状只是简单形状但不显示复合形状时,形状会显示在右侧观察者窗口中。例如,如果我有一个包含 3 个形状的形状列表...形状 1 是一个大圆形,形状 2 是一个复合形状,形状 3 是一个矩形。假设复合形状有 2 个正方形。现在,这将显示大圆形和矩形,但不会显示复合形状组件。我认为一旦我到达了compoundShape,instanceof就会从compoundshape数组中挑选出一个instanceof正方形或矩形

这是复合形状 toString 方法

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;
}

最佳答案

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

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

根据我的理解,应该这样做(getters/setters,省略添加/删除操作):

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;
    }
}

关于java - java中的复合模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521389/

相关文章:

java - 用Java绘制形状

java - 尝试保存和读取文件时出现 java.io.InvalidClassException

Java流来验证映射中的int

java - 出现异常 :javax. mail.AuthenticationFailedException : 550 5. 2.1 无法访问邮箱

c++ - 复合模式 : Copy tree structure

具有完全复合主键/外键支持的 PHP ORM

java - 另一个java通用问题

java - SWT ScrolledComposite 截断信息。

C 中函数指针的复合谓词

hibernate - 使用 Hibernate 和领域驱动设计时如何处理复合模式?