Composite Pattern Demo : Composite Pattern « Design Patterns « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Design Patterns » Composite PatternScreenshots 
Composite Pattern Demo
 
using System;
using System.Text;
using System.Collections;

public abstract class Unit {
    protected string name;
    public abstract void Add(Unit e);
    public abstract void Remove(Unit e);
    public abstract void GetChild(int level);

    public Unit(string name) {
        this.name = name;
    }
}


public class Office : Unit {
    public override void Add(Unit c) {
        Console.WriteLine("Can't use 'Add' in Office!");
    }

    public override void Remove(Unit e) {
        Console.WriteLine("Can't use 'Remove' in Office! ");
    }

    public override void GetChild(int level) {
        Console.WriteLine(new string('*', levelthis.name);
    }

    public Office(string name: base(name) {}
}


public class Branch : Unit {
    private ArrayList node = new ArrayList();

    public override void Add(Unit e) {
        node.Add(e);
    }

    public override void Remove(Unit e) {
        node.Remove(e);
    }

    public override void GetChild(int level) {
        Console.WriteLine(new String('#', levelthis.name);
        foreach (Unit e in this.node)
            e.GetChild(level + 1);

    }

    public Branch(string name: base(name) {}
}

public class Client {
    static void Main(string[] args) {
        Branch root = new Branch("US (Root)");
        Office ny = new Office("A (Unit)");
        Office ca = new Office("B (Unit)");

        root.Add(ny);
        root.Add(ca);

        Branch rootHawaii = new Branch("Canada Branch (Branch)");
        root.Add(rootHawaii);

        Branch branchUK = new Branch("UK Branch (Branch)");
        Office ldnc = new Office("C Office (Unit)");
        Office ldnw = new Office("D Office (Unit)");
        branchUK.Add(ldnc);
        branchUK.Add(ldnw);
        root.Add(branchUK);

        Office dummy = new Office("D Office");
        ldnc.Add(dummy);

        root.GetChild(0);

        root.Remove(rootHawaii);
        branchUK.Remove(ldnc);
        Console.WriteLine("Remove Hawaii branch and London City office");
        root.GetChild(0);
    }
}

 
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.