An Introduction to Visual Basic Design Patterns

Design Patterns in Visual Basic were unwittingly invented by an Austrian born Architect who, as far as I know, had no interest in programming whatsoever!  Christopher Alexander, released his seminal architectural book A Pattern Language: Towns, Buildings, Construction in 1977 which, as well as revolutionising the world of architecture, has unintentionally revolutionised the software industry.  So how did a non-programmer manage to change the world of programmers the world over?  Alexander’s book attempted to decipher a common language and framework where architects could communicate and share ideas with one another using the language and grammar introduced by these patterns in a way they were unable to previously.  The inspiration for his work lay in medieval towns and villages.  They look attractive and harmonious despite the buildings appearing at first glance to be quite distinct from one another.  He came to the conclusion that local regulations at that time were behind this harmonious look of the towns.  These regulations demanded specific features in a property, but also allowed the architect to express himself within this framework.   So he went about defining a language and framework for architects the world over to work within.

Design Patterns

This work didn’t go unnoticed in the word of software.  Although software is much less mature than the world of construction, the two worlds do have a lot in common.  With the introduction of classes and object oriented programming, designers and programmers had a common set of tools to describe and implement applications.  However, every time a team started a new project, they almost always reinvented the wheel, designing systems that had been designed and implemented many many times before.  Although we as programmers and designers had a improved toolset to describe and implement systems, we lacked a common grammar to articulate these systems to people not involved directly with our work.

In 1994, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, now commonly known as the Gang of Four, published a book inspired by Alexander’s work called Design Patterns: Elements of Reusable Object-Oriented Software.  The goal of this book was to introduce a common set of solutions to common problems while providing programmers and designers a language and grammar to express the solutions.  The Gang of Four provided a number of initial problems and solutions they had observed and many authors have built on these, most notably by Steve McConnell in his excellent work Code Complete, which I urge every software developer serious about his craft to own and devour.

The initial work by the Gang of Four developed their solutions in the form of patterns.  These patterns are  based on the following principles.

  • clients remain unaware of the specific types of objects they use, as long as the object adheres to the interface

  • clients remain unaware of the classes that implement these objects; clients only know about the abstract class(es) defining the interface

We are all very aware now of the importance of interfaces.  We’ve proved their worth.  We separated the implementation of our classes from the interface meaning consumers of our class could work with any number of classes that adhere to this interface.  These two principles define what we already know.

There are an library of books devoted to design patterns and their implementations.  This tutorial will introduce one or two of the most common patterns and recommend further reading on the subject.  Of the 23 design patterns put forward by the Gang Of Four the Factory is probably the most famous and well used.  The Factory pattern or Factory Method pattern allows a client to create different types of objects at runtime and access those objects using an interface.  We’ve been doing this to an extent in our previous Collection Class projects but this pattern takes the solution to a new level.

Open up your Collection Class project.

Add a new class to the project called BookCollectionFactory

new class

Paste in the following code:

Public Class BookCollectionFactory

     Public Enum CollectionType
          VBBook
          NonFiction
     End Enum

     Public Function GetBookCollection(ByVal type As CollectionType) As IBookCollection                    Select Case type
               Case CollectionType.VBBook
                    Return New VBBookCollection
               Case CollectionType.NonFiction
                    Return New NonFictionBookCollection
               Case Else
                    Return Nothing
          End Select

     End Function

End Class

The responsibility of this Factory class is to handle the creation handle the creation of objects.

There are two key components to this class:

  • The Enum which defines the types of class that this factory will create
  • The Function GetBookCollection which returns a class of type IBookCollection.  Depending on what is passed to the Function it will return either a new VBBookCollection or a NonFictionBookCollection.  Both of which implement the interface IBookCollection.  This class (and indeed this pattern) is very extensible, meaning it is easilly extended when new classes are added to the project.

In our Form add a new ComboBox called ComboBoxBooks and a new label with the text “Select the collection to maintain” as shown.

 factory design pattern form

At the top of the Form add the following Imports Statement

Imports Imports Collection_Class.BookCollectionFactory

which lets Visual Basic know we plan on using resources in that class.

To populate our new combobox with books to maintain add the following code:

Private Sub AddClassesToComboBox()
     ComboBoxBooks.Items.Add("Non-Fiction Book Collection")
     ComboBoxBooks.Items.Add("Visual Basic Book Collection")
     ComboBoxBooks.SelectedIndex = 0
End Sub

Which populates the ComboBox and sets the index.

In the Form Load event call this Sub rather than the AddBooksToListBox (this will get called elsewhere) as so

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

     ButtonDelete.Visible = False</span>

     AddClassesToComboBox()

End Sub

Add this code to the ComboBox SelectedIndexChanged (an event which fires every time the ComboBox selected item changes).

Private Sub ComboBoxBooks_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBoxBooks.SelectedIndexChanged

     Dim bookCollectionFactory As New BookCollectionFactory

     ListBoxBooks.Items.Clear()
     TextBoxISBN.Text = ""

     Select Case ComboBoxBooks.SelectedIndex
          Case -1
               ComboBoxBooks.SelectedIndex = 0
          Case 0
               BookCollection = bookCollectionFactory.GetBookCollection(CollectionType.NonFiction)
          Case 1
               BookCollection = bookCollectionFactory.GetBookCollection(CollectionType.VBBook)
     End Select

     AddBooksToListBox()

End Sub

This routine asks the Factory class to declare the Book Collection type selected from the combobox and add these item to the now empty Listbox.

Finally, Delete Main.VB from the project.

Run the project.  You’ll get an error stating that Sub Main doesn’t exist and you will be prompted to select Form1 as the new startup object.  Click yes.

Run the project again.

Select a new book collection from the combobox.  Using the Factory Pattern, you can dynamically change the type of book collection at runtime to display, search and maintain.  As long as the class implements the Book Collection interface, this Factory pattern can handle that class.

If you fully understand this then you are more advanced than a large portion of so-called professional software developers.   You are understanding how to write clean, maintainable code which you can describe to your peers.

Write on your resume now that you can implement Design Patterns in Visual Basic.

Excellent work.