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 );
}
}
合成模式与很多其它模式都有联系,将在后续内容中逐步介绍。
相关文章推荐
- C#设计模式(11)-Composite Pattern
- C#设计模式(11)-Composite Pattern
- C#设计模式(11)——外观模式
- C#设计模式之11——外观模式
- C#设计模式(11)-Composite Pattern
- [导入]C#面向对象设计模式纵横谈(11):Facade 外观模式(结构型模式).zip(7.52 MB)
- C#设计模式(11)-Composite Pattern
- 【出版直播】博客园征途系列,《设计模式——基于C#的工程化实现及扩展》今天上市,共飨博客园圣诞大餐
- C#设计模式(8)——桥接模式
- 线程(11)--GUI、适配器设计模式
- 初识设计模式 chapter 11-代理模式
- 设计模式之C#实现(三)FactoryMethod
- C#设计模式——命令模式(Command Pattern)
- 用设计模式固化C#程序
- C#设计模式——模板方法(Template Method)
- C#设计模式——工厂方法模式(Factory Method Pattern)
- C#设计模式——外观模式(Facade Pattern)
- C#设计模式-1、适配器模式(Adapter Pattern)(转载)
- 二十三种设计模式之原型模式的C#实现
- C#设计模式之简单工厂模式(过渡模式)