Compositie Design Pattern
The Gang of Four definition is "Compose objects into tree strutures 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 Compositie Pattern
The code below will produce the out:
MySite
- Products
- - Hats
- - Gloves
- - Boots
- - Sales Items
- - - Sale - Hats
- - - Sale - Gloves
- - - Sale - Boots
- Info
- - Delivery Info
- - About
' 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
Revision number 1, Sunday, March 09, 2008 11:54:32 AM by
This is not the most up to date version of this article. The most recent version can be found here.
You must Login to comment.