合成模式-透明的

來源:互聯網
上載者:User

[關鍵字]:java,design pattern,設計模式,《Java與模式》學習,composite,合成模式

[環境]:StarUML5.0 + JDK6

[作者]:Winty (wintys@gmail.com) http://www.blogjava.net/wintys/

[本文]:

透明的合成模式

package pattern.composite.transparent;import java.util.*;/** * 透明的合成模式:Composite Pattern * @version 2009-6-3 * @author Winty(wintys@gmail.com) */public class TransparentCompositeTest{    public static void main(String[] args){        Graphics g1 , g2;        Graphics p1 , p2;        g1 = new Line();        g2 = new Circle();        p1 = new Picture();        p2 = new Picture();        g1.draw();        g2.draw();        System.out.println("");        p1.add(g1);        p1.add(g2);        p1.draw();        System.out.println("");        p2.add(g1);        p2.add(g2);        p2.add(p1);        p2.draw();    }}/** * 抽象Component角色 */interface Graphics{    void draw();    void add(Graphics g);    void remove(int i);    Graphics getChild(int i);}/** * Leaf角色 */class Line implements Graphics{    @Override    public void draw(){        System.out.println("draw a line");    }    @Override    public void add(Graphics g){    }    @Override    public void remove(int i){    }    @Override    public Graphics getChild(int i){        return null;    }}/** * Leaf角色 */class Circle implements Graphics{    @Override    public void draw(){        System.out.println("draw a circle");    }    @Override    public void add(Graphics g){    }    @Override    public void remove(int i){    }    @Override    public Graphics getChild(int i){        return null;    }}/** * Composite角色 */class Picture implements Graphics{    private List<Graphics> graphics;    public Picture(){        graphics = new ArrayList<Graphics>();    }    @Override    public void draw(){        Iterator<Graphics> it = graphics.iterator();        while(it.hasNext()){            Graphics g = it.next();            g.draw();        }    }    @Override    public void add(Graphics g){        graphics.add(g);    }    @Override    public void remove(int i){        graphics.remove(i);    }    @Override    public Graphics getChild(int i){        return graphics.get(i);    }}

運行結果:

draw a line

draw a circle

draw a line

draw a circle

draw a line

draw a circle

draw a line

draw a circle

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.