Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.
Version 3 (modified by skotku, 14 years ago)
clarifying interface naming convention

Composite Pattern

Part of TutorialDesignPatterns

Description

Examples of implementing the Gang of Four Composite Pattern. You can find description on: http://en.wikipedia.org/wiki/Composite_pattern

Example : Composite Pattern

import std.stdio;

interface IGraphicsOperation /* Component */ {
    void print();
}

class Circle /* Leaf */ : IGraphicsOperation {
    void print() {writefln("Circle");}
}

class Line /* Leaf */ : IGraphicsOperation {
    void print() {writefln("Line");}
}

class Drawing /* Composite */ : IGraphicsOperation {
    IGraphicsOperation[] children;

    void print() {
        writefln("Drawing - begin");
        foreach(child; children) child.print;
        writefln("Drawing - end");
    }

    void add(IGraphicsOperation c) { 
        children~=c;
    }

    void remove(IGraphicsOperation c) {
        for(uint i=0; i<children.length; i++) {
            if (children[i] == c) {
                children = children[0..i] ~ children[i+1..$];
                break;
            }
        }
    }
}

void main() {
    auto subDrawing = new Drawing;
    subDrawing.add(new Circle);
    subDrawing.add(new Circle);
    subDrawing.add(new Line);
    subDrawing.add(new Circle);

    auto drawing = new Drawing;
    drawing.add(new Circle);
    drawing.add(subDrawing);
    drawing.add(new Line);
    auto line = new Line;
    drawing.add(line);
    drawing.add(new Circle);
    drawing.remove(line);

    drawing.print;
}