The Strategy Pattern

04.04.07

    The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. What does this mean?
    From my understanding of the strategy pattern, you are separating the behavior from an object with the use of an interface. The interface defines the family of algorithms and you encapsulate each behavior with a class that implements this interface. With this use of the interface contained in the class you have the ability to reference different behaviors at runtime.
    To better understand this I created a simple app that is a form with a button. When this button is clicked it uses Reflection to load a .dll that contains a class that defines the behavior of the button.



The first thing I did to implement the strategy pattern was to create my interface that defines my family of behaviors/Algorithms.
namespace Patterns.Strategy.PluginInterface
{
    public interface ICrazyBehavior
    {
        void GoCrazy();
    }
}

In order to assign a concrete behavior I created a class that implemented this interface.

using Patterns.Strategy.PluginInterface;
using System.Windows.Forms;
namespace MyUsefullPlugin
{
    class MyUseFullPlugin : ICrazyBehavior
    {
        public void GoCrazy()
        {
            MessageBox.Show("This Plug-in is out of controll");
        }
    }
}


Finally I wrote the class that contains the interface and all other content I needed.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Patterns.Strategy.PluginInterface;
namespace Patterns.Strategy
{
    public partial class PlugableStrategy : Form
    {
        private List<ICrazyBehavior> _crazyBehavior = new List<ICrazyBehavior>();
        public PlugableStrategy()
        {
            InitializeComponent();
        }
        private void btnGoCrazy_Click(object sender, EventArgs e)
        {
            GetPlugins();
            foreach (ICrazyBehavior thisBehavior in _crazyBehavior)
            {
                thisBehavior.GoCrazy();
            }
        }
        // Messy Reflection stuff
        private void GetPlugins()
        {
            _crazyBehavior.Clear();
            string path = Application.StartupPath + "/Plugins";
            string[] files = Directory.GetFiles(path, "*.dll");
            foreach (string file in files)
            {
                try
                {
                    Assembly asm = Assembly.LoadFrom(file);
                    Type[] types = asm.GetTypes();
                    foreach (Type type in types)
                    {
                        Type[] interfaces = type.GetInterfaces();
                        foreach (Type currentInterface in interfaces)
                        {
                            if (currentInterface.Name == "ICrazyBehavior")
                            {
                                if (currentInterface.Namespace == "Patterns.Strategy.PluginInterface")
                                {
                                    object obj = asm.CreateInstance(type.Namespace + "." + type.Name);
                                    _crazyBehavior.Add((ICrazyBehavior)obj);
                                }
                            }
                        }//interface
                    }//type
                }
                catch (Exception) { }
            }//file
        }
    }
}

So, putting this all together I have my form/class that contains a button when some one clicks this button it calls GetPlugins(). The method GetPlugins() uses Reflection to find any .dlls in the plugins folder that contains the ICrazyBehavior interface with the name space of Patterns.Strategy.PluginInterface. If such thing exists in the folder it creates an instance of this object and adds it to my list of _crazyBehaviors once the list is filled the click event continues, it iterates through the list calling the method GoCrazy().

    Using the strategy pattern allowed me to decouple the context class and its behavior enabling me to implement a very "useful" pluggable application.

The Code:

Patterns.zip (83.64 KB)

Web 2.0 Presentation

02.09.07

This video is the coolest most impressive explanation of the buzz word web 2.0 I have ever seen. Definitely worth 5 min of your time.

The Observer Pattern

02.06.07

The observer pattern is very useful and very easy to implement. It only requires two interfaces. One interface is the subject interface the other is the Observer.

    The subject contains three methods: AddObserver, RemoveObserver, and Notify. This interface is implemented by any class that needs to notify other objects that its state has changed.
Public Interface ISubject
    Sub AddObserver(ByRef ob As IObserver)
    Sub RemoveObserver(ByRef ob As IObserver)
    Sub Notify()
End Interface

The other interface is the observer it only contains one method Update, this interface is implemented by any class that needs to be notified by the subject object.

Public Interface IObserver
    Sub Update(ByVal subj As Object)
End Interface
In some examples of this pattern I have seen the subject is setup as an abstract class that you must inherit from, but I believe it limits the usefulness of the pattern. From what I read in the Head First Design Patterns book it says it is best to program to an interface instead of using inheritance. To illustrate this pattern I have created a simple program that monitors My Documents  folder on your computer and notifies a form when ever this folder's contents have changed. This is only an example, the way I implemented the subject object is a little weak but it will serve well enough.

I used the FileSystemWatcher as my base class and implemented the ISubject interface to serve as the subject. The class that implements the subject interface must contain a collection of observers the observers are added and removed using the AddObserver and RemoveObserver methods. The observers are notified by the Notify method witch iterates through the observer collection calling the Update method in the IObserver interface.

Imports System.IO
Public Class MyFileWatcher
    Inherits FileSystemWatcher
    Implements ISubject
Dim _observers As New ArrayList
Public Sub AddObserver(ByRef ob As IObserver) _
  Implements ISubject.AddObserver
    _observers.Add(ob)
End Sub
Public Sub Notify() _
  Implements ISubject.Notify
    Dim ob As IObserver
    For Each ob In _observers
        ob.Update(Me)
    Next
End Sub
Public Sub RemoveObserver(ByRef ob As IObserver) _
  Implements ISubject.RemoveObserver
    _observers.Remove(ob)
End Sub
Private Sub File_Changed _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Changed
    Me.Notify()
End Sub
Private Sub File_Created _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Created
    Me.Notify()
End Sub
Private Sub File_Deleted _
 (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Me.Deleted
    Me.Notify()
End Sub
Private Sub file_Renamed _
    (ByVal sender As Object, ByVal e As System.IO.RenamedEventArgs)Handles Me.Renamed
    Me.Notify()
End Sub
End Class

The observer is implemented as a form that contains List box this list box is Notified by the Subject and the Update method is ran witch updates the list with a valid list of files.

Imports fileWatcher
Imports System.IO
Public Class Form1
    Implements IObserver
    Private _path As String
    Private _allfiles As Collections.ObjectModel.ReadOnlyCollection(Of String)
    Public Property Path() As String
        Get
            Return _path
        End Get
        Set(ByVal value As String)
            _path = value
        End Set
    End Property
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        _allfiles = My.Computer.FileSystem.GetFiles(_path)
        For Each singleFile As String In _allfiles
            Me.ListBox1.Items.Add(singleFile)
        Next
    End Sub
    Public Sub Update1(ByVal subj As Object) Implements fileWatcher.IObserver.Update
        Me.ListBox1.Items.Clear()
        _allfiles = My.Computer.FileSystem.GetFiles(_path)
        For Each singleFile As String In _allfiles
            Me.ListBox1.Items.Add(singleFile)
        Next
    End Sub
End Class

Lastly I created an MDI form that contains an instance of the FileWatcher class and creates a new Instance of the subject form every time a tool strip button is clicked. When ever a file in my documents is update all the child forms of the mdi are updated.

Imports System.Windows.Forms
Imports fileWatcher
Public Class MDIParent1
    Private Sub ShowNewForm(ByVal sender As Object, ByVal e As EventArgs) Handles NewToolStripButton.Click
        Dim FormObserver As New Form1
        FormObserver.MdiParent = Me
        FormObserver.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        _fileWatcherSubject.AddObserver(FormObserver)
        FormObserver.Show()
    End Sub
    Private Sub MDIParent1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        _fileWatcherSubject.Path = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    End Sub
End Class
For complete Observer pattern code download at the following link.

fileWatcher.zip (116.6 KB)

I' m Learning Design Patterns

01.26.07

I received a great book from my girl friend this Christmas called Head First Design Patterns. I have been reading this book and it is really getting me excited (about coding patterns in case you needed clarification). To better understand these patterns I am going to try and code examples of each one and post my experience as well as the code on my blog. I will list the patterns so I can keep track of them as well as giving my one or two readers a heads up on what to expect.

All of these patterns and definitions are described in Head First Design Patterns by Eric Freeman & Elisabeth Freeman with Kathy Sierra & Bert Bates from O'Reilly

Design patterns

  • The Strategy Pattern (p24) - Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  • The Observer Pattern (p51) - Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • The Decorator Pattern (p91) - Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • The factory Method Pattern (p134) - Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • The Abstract Factory Pattern(p156) - Provides an interface for creating families of related of dependent objects without specifying their concrete classes.
  • The Singleton Pattern (p177) - Ensures a class has only one instance, and provides a global point of access to it.
  • The Command Pattern (p206) - Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.
  • The Adapter Pattern (p243) - Converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • The Template Method Pattern(p289) - Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Methods lets subclasses redefined certain steps of an algorithm without changing the algorithm's structure.
  • The Interator Pattern (p336) - Provides a way to access the elements of an aggregate object sequentially without exposing the underlying representation.
  • The Composite Pattern(p356) - Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • The State Pattern(p410) - Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
  • The proxy pattern(p460) -  Provides a surrogate or placeholder for another object to control access to it.

My Wish List

12.22.06

I think one of the hardest parts of becoming a successful and educated programmer (besides just sitting down and coding) is finding good tools and resources to learn from and use. I put a lot of effort into finding these. In order to find these tools and recourses I look toward programmers I consider successful, most of which are listed under the Developer and Technologist Journals on my site. So far I have found frequent references to the following books and tools, these are on my to read/buy list.

Book Wish List
Tools Wish List
Tools and Resources I Own & Recommend
  • Reflector for .NET - Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows you to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL.
  • Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers.
  • Head First Design Patterns:  I got this book for Christmas, thank you Minette and Jesse, it is an entertaining read and easy to understand.