合成(Composite)模式
2011-09-08 15:21
169 查看
C#设计模式(11)-Composite Pattern
分类: 设计模式 2006-11-10 20:30 185人阅读 评论(0) 收藏 举报一、 合成(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
{
{
// 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 );
}
}
合成模式与很多其它模式都有联系,将在后续内容中逐步介绍。
相关文章推荐
- 合成(Composite)模式
- C# 设计模式--合成模式(Composite)
- 【设计模式】之 Composite 合成模式
- 合成模式 :Composite(转自阿良.NET)
- 九、 合成(Composite)模式 --结构模式(Structural Pattern)
- 合成模式(Composite) -- (模式之六)
- 讲故事学设计模式-合成(Composite)模式
- 学习php设计模式 php实现合成模式(composite)
- 合成(Composite)模式
- 设计模式c#语言描述——合成(Composite)模式
- 合成(Composite)模式
- 合成(Composite)模式
- 合成(Composite)模式
- 《Java与模式》学习笔记:设计模式——合成(Composite)模式
- 设计模式——合成模式(Composite)
- Composite 合成模式可以让客户程序把单个基本对象和对象的合成用一种统一的方式进行处理
- 合成(Composite)模式
- Java设计模式——合成模式(Composite)
- 设计模式c#语言描述——合成(Composite)模式
- 设计模式c#语言描述——建造者模式、适配器模式、合成(Composite)模式