Design Pattern : Composite Pattern

一个最简单的组合模式的使用例子 

1. 问题描述

计算一个网络中的计算机个数(拓扑结构为树型):

               

2. 实现(根据Design Patterns一书)

using System;
using System.Text;
using System.Collections;

abstract class Component
{
   protected string name;
   public Component(string name) { this.name = name; }
   public abstract void Add(Component com);
   public abstract int  Count();
}


class Composite : Component
{
    private ArrayList children = new ArrayList();
    public Composite(string name) : base( name ){}
    public override void Add( Component com ) { children.Add( com ); }
    public override int Count()
    {
        int sum = 1;
        foreach(Component com in children)
        {
            sum += com.Count();
        }
        return sum;
    }
}

class Leaf : Component
{
    public Leaf(string name) : base (name){ }
    public override void Add( Component com) 
    { 
        Console.WriteLine("Connot add to a leaf");
    }
    public override int  Count(){ return 1; }
}

class Client
{
    public static void Main( string[] args)
    {
        Composite root = new Composite("Root");

            root.Add( new Leaf("Leaf A"));
            root.Add( new Leaf("Leaf B"));
        
            Composite com = new Composite("Composite X");

                com.Add( new Leaf("Leaf XA"));
                com.Add( new Leaf("Leaf XB"));

        root.Add( com );
        

        Console.WriteLine("节点总数:" + root.Count());
        Console.ReadKey();
    }
}

3. 问题

如何将拓扑结构保存在xml文档中,动态加载,计算出结果。

4. 重点

  • 在于理解该模式的应用类型,树形结构,整体——部分;
  • 关键在于抽象类可以代表 Leaf 和 Composite 去执行他们的方法;
  • 实现时还要考虑安全性,透明性问题。
  • 参与者:Component, Leaf, Composite, Client
原文地址:https://www.cnblogs.com/wangshide/p/2508288.html