📄 class1.cs
字号:
using System;
namespace GrahpicDrawing
{
using System;
using System.Collections;
//定义 部件抽象类Component
abstract class DrawingElement
{
protected string name;
public DrawingElement( string name )
{
this.name = name;
}
abstract public void Add( DrawingElement d );
abstract public void Remove( DrawingElement d );
abstract public void Display( int indent );
}
//Leaf 定义叶部件
class PrimitiveElement : DrawingElement
{
public PrimitiveElement( string name ) : base( name ) {}
public override void Add( DrawingElement c )
{
Console.WriteLine("Cannot Add");
}
public override void Remove( DrawingElement c )
{
Console.WriteLine("Cannot Remove");
}
public override void Display( int indent )
{
Console.WriteLine( new String( '-', indent ) +
" draw a {0}", name );
}
}
// 定义组合类,从部件抽象类派生出来,"Composite"
class CompositeElement : DrawingElement
{
private ArrayList elements = new ArrayList();
//调用父类的构造函数
public CompositeElement( string name )
: base( name ) {}
public override void Add( DrawingElement d )
{
elements.Add( d );
}
public override void Remove( DrawingElement d )
{
elements.Remove( d );
}
public override void Display( int indent )
{
Console.WriteLine( new String( '-', indent ) +
"+ " + name );
// 显示节点每一个子元素
foreach( DrawingElement c in elements )
c.Display( indent + 2 );
}
}
/// <summary>
/// 组合应用的测试
/// </summary>
public class CompositeApp
{
public static void Main( string[] args )
{
//生成一个树的结构
CompositeElement root = new
CompositeElement( "Picture" );
root.Add( new PrimitiveElement( "Red Line" ));
root.Add( new PrimitiveElement( "Blue Circle" ));
root.Add( new PrimitiveElement( "Green Box" ));
CompositeElement comp = new
CompositeElement( "Two Circles" );
comp.Add( new PrimitiveElement( "Black Circle" ) );
comp.Add( new PrimitiveElement( "White Circle" ) );
root.Add( comp );
//增加并且删除叶部件
PrimitiveElement l = new
PrimitiveElement( "Yellow Line" );
root.Add( l );
root.Remove( l );
//递归显示所有节点
root.Display( 1 );
Console.Read();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -