Composite Design Pattern
The Gang of Four definition is "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly".
In the example below we use the Composite pattern to display a site map.
A VB example of the Composite Pattern
The code below will produce the output:
MySite
- Products
- - Hats
- - Gloves
- - Boots
- - Sales Items
- - - Sale - Hats
- - - Sale - Gloves
- - - Sale - Boots
- Info
- - Delivery Info
- - About
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"))
siteRoot.displaySelfAndChildren("")
Public Interface INode
ReadOnly Property Name() As String
Sub displaySelfAndChildren(ByVal Indent As String)
End Interface
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))
_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
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
UML Diagram
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.