I'm working on a program right now that allows you to create shapes (square, rectangles and circles) you also have an option to create a compound shape by selecting already created shapes...I'm using two observers for the shapes. One for squares/rectangles and one for large circles and these observers list the reference points and sizes of the shapes. When a compound shape is created it should list the components in the square/rectangle frame if there are squares/rectangles in the compound shape.
I'm supposed to create the compound shape using composite pattern. So basically compound shapes and my circles, squares and rectangles need to be handled the same way
I have an array of objects called shapes, and compound shape is an object with an array of shapes in it.
My question is how can I check through the shapes array for an object of type compound shape and then check through the compound shapes array for an instance of rectangle or square?
Sorry for not including code but my program is somewhat large with a lot of classes
heres the methods I use to check for an instance of square or rectangle...these two methods are in two different classes. The shapes display in the right observer window when theyre just the simple shapes but the compound shapes dont display. If for example I had a shape list with 3 shapes...shape 1 is a large circle, shape 2 is a compound shape and shape 3 is a rectangle. And lets say the compound shape has 2 squares. Right now this would display the large circle and the rectangle but it wont display the compound shape components. I thought that once I got to the compoundShape, instanceof would look pick out an instanceof square or rectangle from the compundshape array
heres the compound shapes toString method
public String toString(){
String output="";
output += "Compound Shape: /n";
for (int i = 0; i< numShapes; i++){
output += shapes[i].toString();
}
return output;
}
heres the do method I use to look for an instance of square or rectangle
do {//squares rectangles
currentShape = shapes.getShape();
if (shapes.squareRectangleFinder())
outputString1 += currentShape.toString();
}while (shapes.next());
and heres the square finder method
public boolean squareRectangleFinder() {
if ((shapes[currentShape] instanceof Square)||(shapes[currentShape] instanceof Rectangle)){
return true;
}
return false;
}
instanceofoperator to check if the element in the array is an instance of the CompoundShape class.squareRectangleFinder()problem for example can be solved if you add a methodisRectangular()toShape. If that is an important property of all shapes, make it one for all. Or add a classRectangularShapewhich defines this property and subclassRecangleandSquarefrom there.instanceof. - You just have to implement the same functionality on a CompoundShape that you do on a normal one.