Category Archives: Design Patterns

Disposing Resources

When you are working with managed resources in C#. you can usually let the Garbage Collector deal with tidying up after you. Memory allocation problems that are familiar in the past with languages such as C are dealt with for you.

The Garbage Collector is not magic. First off you don’t usually control when garbage collection occurs. The Framework will initiate collection whenever it thinks it’s necessary. Sometimes you’ll go a long time between collections, but as resources begin to become scarce, it will happen more often.

You can call a forced collection, but it’s rare that this isĀ  a good idea. The Garbage Collector itself will manage when collections need to occur. Forcing multiple early collections is almost always worse than letting the collection happen automatically.

The Garbage Collector cannot deal with unmanaged resources. The most common of these that you will encounter are related to database connections, and file access.

You should do two things when dealing with unmanaged resources. First off, wrap them in using statements. This ensures that the dispose method is called once you are finished with the resource.

The second thing to do is to make sure that your classes implement the IDisposable interface. This means that when the Dispose() method is called you have a chance to clean up your unmanaged resources, to prevent any memory leaks and ensure that the Garbage Collector can do it’s job.

There are a lot of further complexities to the Garbage Collection and memory management, most of the time you won’t have to worry too much about them, but it’s good to know the basics for the times you do.

Advertisements

Factory Pattern

When we are designing systems we can make use of a variety of deign patterns. They are valuable for many reasons, not least that using a common and understood way of designing something means that it will be easily understood by people familiar with the pattern.

The Factory Design pattern can be used when you have a large number of similar objects (so can be referred to through a common interface or abstract class), and where you wish to hide the instantiation logic from the calling class.

Consider a simple drawing program. You might want to create one of a large number of types of shape, square, circle, triangle etc.

We can use a Factory class to return an instance of the type of shape we want:


public abstract class Shape
{
  public abstract Shape createShape();
}

public class Square : Shape
{
  public Square() {}

  public override Shape createShape()
  {
    return new Square();
  }
}

public class ShapeFactory
{
  Dictionary<string, Shape> registeredShapes;

  private static readonly ShapeFactory instance = new ShapeFactory();

  private ShapeFactory()
  {
    registeredShapes = new Dictionary<string, Shape>();
    var Shapes = from b in Assembly.GetExecutingAssembly().GetTypes()
                 where b.IsSubclassOf(typeof(Shape))
                 select b;

    foreach (var type in Shapes)
    {
      var s = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);
      registeredShapes.Add(type.Name, (Shape)s);
    }
  }

  public static ShapeFactory Instance
  {
    get
    {
       return instance;
    }
  }

  public Shape createShape(string shapeName)
  {
    return ((Shape)registeredShapes[shapeName]).createShape();
  }
}

From this we can simply call ShapeFactory.Instance.createShape(“Square”); and this will give us a new instance of the Square object.

As we expand to define extra types of shape, we won’t need to alter the Factory, we can just implement the new shape, it will be discovered automatically, thanks to the use of reflection.

Whilst this is clearly a simple example, where we are just creating and return the objects, it should be easy to see that we can use much more complicated objects. We would hide all the creation logic inside each type, and use the factory to pass an fully created concrete instance whenever one is required.