将物件组织成数状结构,并且让客户端以一致性的方式对待个别物件或者组合
public class Circle extends Graphics {
@Override
public void draw() {
DebugLog.log("draw circle");
}
}
public abstract class Graphics {
public abstract void draw();
}
public class Line extends Graphics {
@Override
public void draw() {
DebugLog.log("draw line");
}
}
public class Picture extends Graphics {
private List<Graphics> graphicsList = new ArrayList<Graphics>();
public void add(Graphics graphics) {
graphicsList.add(graphics);
}
public void remove(Graphics graphics) {
graphicsList.remove(graphics);
}
@Override
public void draw() {
int size = graphicsList.size();
for (int index = 0; index < size; index++) {
Graphics graphics = graphicsList.get(index);
graphics.draw();
}
}
}
public class Rectangle extends Graphics {
@Override
public void draw() {
DebugLog.log("draw rectangle");
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Graphics circle=new Circle();
Graphics line=new Line();
Graphics rectangle=new Rectangle();
Picture firstPicture=new Picture();
firstPicture.add(circle);
firstPicture.add(line);
firstPicture.add(rectangle);
Picture secondPicture=new Picture();
secondPicture.add(rectangle);
secondPicture.add(firstPicture);
secondPicture.draw();
}
}