上一篇,总结了结构模式的一些特点,这一篇分别介绍两种方式的实现。
这里我们用绘图这个例子来说明Composite模式,通过一些基本图像元素(直线、圆等)以及一些复合图像元素(由基本图像元素组合而成)构建复杂的图形树。在设计中我们对每一个对象都配备一个draw()方法,在调用时,会显示相关的图形。可以看到,这里复合图像元素(Picture1、Picture)它在充当对象的同时,又是那些基本图像元素的一个容器。
透明方式:
根节点:
package composite;
public interface Graphics1 {
void draw();
void add(Graphics1 g);
void remove(Graphics1 g);
Graphics1 gotChild(int i);
}
树叶节点:
package composite;
public class Line1 implements Graphics1 {
public void draw(){
System.out.println("Drawing Line");
}
public void add(Graphics1 g){
return;
}
public void remove(Graphics1 g){
return;
}
public Graphics1 gotChild(int i){
return null;
}
}
package composite;
public class Circle1 implements Graphics1 {
public void draw(){
System.out.println("Drawing Circle");
}
public void add(Graphics1 g){
return;
}
public void remove(Graphics1 g){
return;
}
public Graphics1 gotChild(int i){
return null;
}
}
package composite;
public class Rectangle1 implements Graphics1 {
public void draw(){
System.out.println("Drawing Rectangle");
}
public void add(Graphics1 g){
return;
}
public void remove(Graphics1 g){
return;
}
public Graphics1 gotChild(int i){
return null;
}
}
树枝节点:
package composite;
import java.util.Vector;
public class Picture1 implements Graphics1 {
private Vector list = new Vector(10);
public void draw(){
for (int i = 0; i < list.size(); i++) {
Graphics1 g = (Graphics1) list.get(i);
g.draw();
}
}
public void add(Graphics1 g){
list.add(g);
}
public void remove(Graphics1 g){
list.remove(g);
}
public Graphics1 gotChild(int i){
return (Graphics1)list.get(i);
}
}
客户端调用:
package composite;
public class Client1 {
private static Picture1 picture= new Picture1();
public static void main(String[] args){
picture.add(new Circle1());
picture.add(new Line1());
picture.add(new Rectangle1());
picture.draw();
}
}
安全方式:
根节点:
package composite;
public interface Graphics {
void draw();
}
树叶节点:
package composite;
public class Circle implements Graphics {
public void draw(){
System.out.println("Drawing Circle");
}
}
package composite;
public class Line implements Graphics {
public void draw(){
System.out.println("Drawing Line");
}
}
package composite;
public class Rectangle implements Graphics {
public void draw(){
System.out.println("Drawing Rectangle");
}
}
树枝节点:
package composite;
import java.util.Vector;
public class Picture implements Graphics {
private Vector list = new Vector(10);
public void draw(){
for (int i = 0; i < list.size(); i++) {
Graphics g = (Graphics) list.get(i);
g.draw();
}
}
public void add(Graphics g){
list.add(g);
}
public void remove(Graphics g){
list.remove(g);
}
public Graphics gotChild(int i){
return (Graphics)list.get(i);
}
}
客户端调用:
package composite;
public class Client {
private static Picture picture= new Picture();
public static void main(String args[]){
picture.add(new Circle());
picture.add(new Line());
picture.add(new Rectangle());
picture.draw();
}
}