C#设计模式(11)-Composite Pattern
2010-04-30 11:31
295 查看
一、 合成(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 );
}
}
合成模式与很多其它模式都有联系,将在后续内容中逐步介绍。
参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社
相关文章推荐
- C#设计模式(11)——外观模式
- C#设计模式(11)-Composite Pattern
- C#设计模式(11)-Composite Pattern
- C#设计模式(11)-Composite Pattern
- C#设计模式之11——外观模式
- [导入]C#面向对象设计模式纵横谈(11):Facade 外观模式(结构型模式).zip(7.52 MB)
- C#设计模式(11)-Composite Pattern
- 《模式——工程化实现及扩展》(设计模式C# 版)《创建者模式 Builder》——“自我检验" 参考答案
- c#设计模式-桥梁模式
- C#设计模式(1)——单例模式
- C#设计模式之十三模板方法模式(Template Method Pattern)【行为型】
- C#设计模式之二十职责链模式(Chain of Responsibility Pattern)【行为型】
- C#设计模式(8)-Builder Pattern
- 乐在其中设计模式(C#) - 状态模式(State Pattern)
- C#设计模式之二工厂方法模式(Factory Method Pattern)【创建型】
- 设计模式c#描述——装饰(Decorator)模式
- 单例设计模式(C#) 简单模式
- 用设计模式固化C#程序
- C#设计模式总结
- 设计模式11_策略模式