复合





4.00/5 (1投票)
复合设计模式“四人帮”的定义是:“将对象组合成树形结构以表示部分-整体层次关系。复合模式使得客户端能够以统一的方式处理单个对象和对象组合。”
复合设计模式
“四人帮”的定义是:“将对象组合成树形结构以表示部分-整体层次关系。复合模式使得客户端能够以统一的方式处理单个对象和对象组合。”
在下面的示例中,我们使用复合模式来显示站点地图。
VB 中复合模式的示例
下面的代码将产生以下输出
MySite
- 产品
- - 帽子
- - 手套
- - 靴子
- - 促销商品
- - - 促销 - 帽子
- - - 促销 - 手套
- - - 促销 - 靴子
- 信息
- - 配送信息
- - 关于
' This code can be run in the page behind section
Dim items As New Section("Products")
Dim information As New Section("Info")
Dim saleItems As New Section("Sales Items")
siteRoot.AddNode(items)
siteRoot.AddNode(information)
items.AddNode(New Page("Hats"))
items.AddNode(New Page("Gloves"))
items.AddNode(New Page("Boots"))
items.AddNode(saleItems)
saleItems.AddNode(New Page("Sale - Hats"))
saleItems.AddNode(New Page("Sale - Gloves"))
saleItems.AddNode(New Page("Sale - Boots"))
information.AddNode(New Page("Delivery Info"))
information.AddNode(New Page("About")) ' Display the site layout
siteRoot.displaySelfAndChildren("")
' All Sections and Pages must implement this interface
Public Interface INode
ReadOnly Property Name() As String
Sub displaySelfAndChildren(ByVal Indent As String)
End Interface
' The Section class that contains the pages (Branch).
Public Class Section
Implements INode
Private _Name As String
Private _ChildNodes As New ArrayList
Private _Indent As String = " - "
Public Sub New(ByVal Name As String)
_Name = Name
End Sub
Public Sub displaySelfAndChildren(ByVal Indent As String) Implements INode.displaySelfAndChildren
HttpContext.Current.Response.Write(String.Format("{0}{1}</br>", Indent, _Name))
' NOTE: We use the _indent variable only for demo purposes
_Indent = _Indent & Indent
For Each aNode As INode In _ChildNodes
aNode.displaySelfAndChildren(_Indent)
Next
End Sub
Sub AddNode(ByRef aNode As INode)
_ChildNodes.Add(aNode)
End Sub
Public ReadOnly Property Name() As String Implements INode.Name
Get
Return _Name
End Get
End Property
End Class
' The Page Node (Leaf).
Public Class Page
Implements INode
Private _Name As String
Public Sub New(ByVal Name As String)
_Name = Name
End Sub
Public Sub displaySelfAndChildren(ByVal Indent As String) Implements INode.displaySelfAndChildren
HttpContext.Current.Response.Write(String.Format("{0}{1}</br>", Indent, _Name))
End Sub
Public ReadOnly Property Name() As String Implements INode.Name
Get
Return _Name
End Get
End Property
End Class