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 lives of software developers the world over.  So how did a non-programmer manage to achieve this?

Alexander’s book attempted to create a common language and framework whereby architects could communicate with one another using a pattern based language 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 that architects the world over could 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 building 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 to solve problems that had been solved many, many times before.  Although we as programmers and designers had an enhanced tool-set 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 twofold:

  1. to introduce a common set of solutions to common problems
  2. to provide programmers and designers with a language and grammar to express these solutions

The Gang of Four provided a number of problems and solutions they had observed and many authors have built on these, most notably by Steve McConnell in his excellent work Code Complete (a book every software developer serious about his craft should 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.  And it is our abstract base class that implemented the interface, not the concrete classes.  These two principles define what we already know.

There’s a 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 solely to create book collection objects.  Our Form can request a Non Fiction Book Collection from the Factory class, and the Factory class sole responsibility is to create one and hand it over.   And that’s it!  As developers we then have added flexibility.  We can move the classes to another project and the Form will never know, we just need to update the Factory class.   If there are many Forms in the application, we only have to update the one Factory class rather than the many Forms.  The application is automatically more maintainable with the addition of these relatively few lines of code.

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 easily 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 Collection_Class.BookCollectionFactory

This lets Visual Basic know we plan on using resources in that Namespace.

To populate our new ComboBox with books, 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 SelectedIndex to 0 (selecting the first item in the ComboBox).

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

     AddClassesToComboBox()

End Sub

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

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 new Factory class to create a book collection object of the type selected from the combobox.  The items in this new collection are added 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.  It should work.  Select a new book collection from the ComboBox.  Using the Factory Pattern, you can dynamically change the book collection.  As long as the class implements the Book Collection interface, this Factory pattern can handle that class.  It is the Factory Classes responsibility to create these classes.   Now if the classes move to another project altogether, the Form never knows (and never needs to know).  Your application is now far more flexible and is much easier to maintain.

If you fully understand this then you are more advanced than a large portion of so called professional software developers.   You understand 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!

If you don’t fully understand, don’t worry!  Take a look at the video and take time to digest what we have learnt here.  It may take a bit time, but it is worth it.  These are pretty advanced concepts now and they may take time to digest.  When they do, you won’t be sorry!