Structural Patterns -- Composite

博客涉及字符串、类、结构等信息技术概念,还提到了输出和树相关内容,但因内容缺失,关键信息难以更详细概括。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

// Composite pattern -- Structural example

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

// "Component"


abstract
class Component

{
  // Fields
  protected string name;

 
// Constructors
  public Component( string name )
  {
    this.name = name;
  }

 
// Methods
  abstract public void Add(Component c);
  abstract public void Remove( Component c );
  abstract public void Display( int depth );
}

// "Composite"


class
Composite : Component

{
  // Fields
  private ArrayList children = new ArrayList();

 
// Constructors
  public Composite( string name ) : base( name ) {}

 
// Methods
  public override void Add( Component component )
  {
    children.Add( component );
  }
  public override void Remove( Component component )
  {
    children.Remove( component );
  }
  public override void Display( int depth )
  {
    Console.WriteLine( new String( '-', depth ) + name );

   
// Display each of the node's children
    foreach( Component component in children )
      component.Display( depth + 2 );
  }
}

// "Leaf"


class
Leaf : Component

{
  // Constructors
  public Leaf( string name ) : base( name ) {}

 
// Methods
  public override void Add( Component c )
  {
    Console.WriteLine("Cannot add to a leaf");
  }

  public
override void Remove( Component c )

  {
    Console.WriteLine("Cannot remove from a leaf");
  }

  public
override void Display( int depth )

  {
    Console.WriteLine( new String( '-', depth ) + name );
  }
}

///
<summary>

/// Client test
/// </summary>
public class Client
{
  public static void Main( string[] args )
  {
    // Create a tree structure
    Composite root = new Composite( "root" );
    root.Add( new Leaf( "Leaf A" ));
    root.Add( new Leaf( "Leaf B" ));
    Composite comp = new Composite( "Composite X" );

   
comp.Add( new Leaf( "Leaf XA" ) );

    comp.Add( new Leaf( "Leaf XB" ) );
    root.Add( comp );

   
root.Add( new Leaf( "Leaf C" ));


   
// Add and remove a leaf
    Leaf l = new Leaf( "Leaf D" );
    root.Add( l );
    root.Remove( l );

   
// Recursively display nodes
    root.Display( 1 );
  }
}

Output
-root
---Leaf A
---Leaf B
---Composite X
-----Leaf XA
-----Leaf XB
---Leaf C

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值