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/archive/2012/05/18/2508288.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值