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.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
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
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.