Inversion of Control vs Dependency Injection vs Strategy Pattern

02.18.09

Warning this my understanding as of today, who knows what tomorrow will bring.

I often hear the terms Inversion of Control(IOC), Dependency Injection(DI) and the Strategy Pattern thrown around in the same context, this was getting really confusing for me. So, I spent a couple of hours trying to clarify the differences.

IOC vs DI: Basically DI is a type of IOC. IOC is a broad abstract principle that covers not only DI but Event-Driven programming and numerous others.

So What is DI? DI is the way you provide the implementation for a dependent service. There are a number of DI frameworks out there I have recently been playing with Ninject mostly because I like ninjas... and the flow syntax for wiring up the dependencies looks nice.

DI vs Strategy Pattern: For a while now I have been using the Strategy pattern thinking it was the same as DI. I know, "Gosh such an idiot :p", but DI assembles the appropriate algorithms for the calling class. Strategy is just one of the patterns that lends itself well to DI.

More Info:

Dependency injection

Inversion of control

Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler

Inversion of Control vs Strategy Pattern

IoC containers are not about a design pattern

Thank you, Eric Ridgeway for answering my 200 questions.

Singleton Pattern

09.14.07

The singleton pattern in C# is very simple to implement and very useful. This pattern ensures that there is only one instance of its self providing a global point of access. There are different ways of doing this but I like to use the example below  because it is thread safe and clean.

public class User
{
     private int _userId = 1;
     private static User _instance = new User();
     static User()
     {
     }
     private User()
     {
     }
     public int UserId
     {
         get
         {
             return _userId ;
         }
         set
         {
             _userId = value;
         }
     }
     public static User Instance
     {
         get
         {
             return _instance;
         }
     }
}

Here is a quick test I wrote in NUnit that shows how it is used and comfirms there is only one instance.

[Test]
public void TestSingleton()
{
     User sngle1 = User.Instance;
     sngle1.UserId = 1;
     User sngle2 = User.Instance;
     sngle2.UserId = 2;
     Assert.AreEqual(sngle2.UserId, sngle1.UserId);
}

More Info:
Everything you need to know about C# singleton.
More Patterns

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.