📄 compoundshape.java
字号:
package composite;
import java.util.ArrayList;
public class CompoundShape implements Shape {
private ArrayList children = new ArrayList ();
private String name ;
private Shape parent =null ;
private int iterationIndex = 0;
public static class Iterator {
private CompoundShape rootNode;
private CompoundShape contextNode;
boolean hasNextFlag = true;
boolean isSpecialCase = false;
public Iterator (CompoundShape t) {
rootNode = t;
contextNode = rootNode;
rootNode.initIteration ();
hasNextFlag = true;
int lastIndex = t.children .size ()- 1;
Object obj = contextNode .children .get (lastIndex );
if (obj .getClass () == CompoundShape .class ){
isSpecialCase = true ;
}
}
public boolean hasNext () {
return hasNextFlag ;
}
public PrimitiveShape next () {
PrimitiveShape s = null ;
int index = contextNode .iterationIndex ;
int upperLimit = contextNode .children .size ();
int i;
Object obj = null ;
for (i = index ; i < upperLimit ; ++i){
obj = contextNode .children .get (i);
contextNode .iterationIndex = i+1;
if (obj .getClass () == CompoundShape .class ){
contextNode = (CompoundShape )obj ;
s = next ();
break ;
}
else {
s = (PrimitiveShape )obj ;
break ;
}
}
if ( isSpecialCase == false && contextNode == rootNode && i == upperLimit -1) {
hasNextFlag = false ;
}
if (i == upperLimit - 1 && obj.getClass () != CompoundShape.class) {
contextNode = (CompoundShape) contextNode.getParent ();
}
if (isSpecialCase == true && contextNode == rootNode &&
i == upperLimit - 1) {
hasNextFlag = false;
}
return s;
} // end next()
} // end class Iterator
private void initIteration () {
iterationIndex = 0;
java.util.Iterator itr = children.iterator ();
while (itr.hasNext ()) {
Object obj = (Shape) itr.next ();
if (this.getClass () == obj.getClass ()) {
( (CompoundShape) obj).iterationIndex = 0;
}
}
}
public CompoundShape () {
iterationIndex = 0;
}
public Shape getParent () {
return parent;
}
public void setParent (Shape s) {
parent = s;
}
public String getName () {
return name;
}
public void setName (String n) {
name = n;
}
public void addShape (Shape shape) {
children.add (shape);
shape.setParent (this);
}
public void removeShape (Shape shape) {
children.remove (shape);
}
public void printChildren () {
java.util.Iterator itr = children.iterator ();
while (itr.hasNext ()) {
System.out.println ( ( (Shape) itr.next ()).getName ());
}
}
public void draw () {
java.util.Iterator itr = children.iterator ();
while (itr.hasNext ()) {
( (Shape) itr.next ()).draw ();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -