您的位置:首页 > 编程语言 > C#

C#设计模式(11)-Composite Pattern

2007-09-30 09:21 316 查看

一、 合成(Composite)模式

合成模式有时又叫做部分-整体模式(Part-Whole)。合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。

从和尚的故事谈起

这是小时候我奶奶讲的故事:从前有个山,山里有个庙,庙里有个老和尚在给小和尚讲故事,讲的什么故事呢?从前有个山,山里有个庙……。奶奶的故事要循环多少次,根据你多长时间睡着而定。在故事中有山、有庙、有和尚、有故事。因此,故事的角色有两种:一种里面没有其它角色;另一种内部有其它角色。

对象的树结构

一个树结构由两种节点组成:树枝节点和树叶节点。树枝节点可以有子节点,而一个树叶节点不可以有子节点。除了根节点外,其它节点有且只有一个父节点。

注意:一个树枝节点可以不带任何叶子,但是它因为有带叶子的能力,因此仍然是树枝节点,而不会成为叶节点。一个树叶节点永远不可能带有子节点。


二、 合成模式概述

下图所示的类图省略了各个角色的细节。

// Composite pattern -- Structural example
using System;
using System.Text;
using System.Collections;

// "Component"
abstract class Component

// "Composite"
class Composite : Component

// "Leaf"
class Leaf : Component

public class Client
// Composite pattern -- Structural example

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

// "Component"
abstract class Component

// "Composite"
class Composite : Component

// "Leaf"
class Leaf : Component

public class Client
// Composite pattern -- Real World example

using System;
using System.Collections;

// "Component"
abstract class DrawingElement

// "Leaf"
class PrimitiveElement : DrawingElement

// "Composite"
class CompositeElement : DrawingElement

public class CompositeApp
public static void Main( string[] args )
// Create a tree structure
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 );

// Add and remove a PrimitiveElement
PrimitiveElement l = new PrimitiveElement( "Yellow Line" );
root.Add( l );
root.Remove( l );

// Recursively display nodes
root.Display( 1 );
}
}
合成模式与很多其它模式都有联系,将在后续内容中逐步介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: