組合模式-虛有其表的模式

組合模式:java

1.做用:spa

把多個對象組成樹狀結構來表示局部與總體,這樣用戶能夠同樣的對待單個對象和對象的組合。code

2.例子對象

/** "Component" */
interface Graphic {
 
    //Prints the graphic.
    public void print();
}
 
/** "Composite" */
import java.util.List;
import java.util.ArrayList;
class CompositeGraphic implements Graphic {
 
    //Collection of child graphics.
    private List<Graphic> childGraphics = new ArrayList<Graphic>();
 
    //Prints the graphic.
    public void print() {
        for (Graphic graphic : childGraphics) {
            graphic.print();
        }
    }
 
    //Adds the graphic to the composition.
    public void add(Graphic graphic) {
        childGraphics.add(graphic);
    }
 
    //Removes the graphic from the composition.
    public void remove(Graphic graphic) {
        childGraphics.remove(graphic);
    }
}
 
/** "Leaf" */
class Ellipse implements Graphic {
 
    //Prints the graphic.
    public void print() {
        System.out.println("Ellipse");
    }
}
 
/** Client */
public class Program {
 
    public static void main(String[] args) {
        //Initialize four ellipses
        Ellipse ellipse1 = new Ellipse();
        Ellipse ellipse2 = new Ellipse();
        Ellipse ellipse3 = new Ellipse();
        Ellipse ellipse4 = new Ellipse();
 
        //Initialize three composite graphics
        CompositeGraphic graphic = new CompositeGraphic();
        CompositeGraphic graphic1 = new CompositeGraphic();
        CompositeGraphic graphic2 = new CompositeGraphic();
 
        //Composes the graphics
        graphic1.add(ellipse1);
        graphic1.add(ellipse2);
        graphic1.add(ellipse3);
 
        graphic2.add(ellipse4);
 
        graphic.add(graphic1);
        graphic.add(graphic2);
 
        //Prints the complete graphic (four times the string "Ellipse").
        graphic.print();
    }
}

這個模式太簡單了,它有肯定的用途,將不一樣的對象有統一操做方式,無論是符合對象,仍是單一對象。blog

我想它更多的場景特色。太過於虛有其表,以致於歷來沒有把它放在心上,不會有專門人在這種場景下,定義類名爲composite。three

相關文章
相關標籤/搜索