sloppycode.net
Software Design Patterns in C#
Common software design patterns in C#.


Introduction

Download example solution

Below are 7 design patterns given with example source code and a brief summary of each along with an example usage of the pattern. The idea is to keep the summary and example brief, an overview instead of an in-depth description of each. If you are after more detailed information on each pattern have a look at the links section at the end of the article, which includes books. These books along with the information online are where I've based my source code and descriptions from, and also from using them over the years -sometimes without realising its a known pattern and other times deliberately.

I haven't included any UML class diagrams to try to keep the article concise. If you find UML explains the class/interface relationships better then the Gang of Four and O'Reilly C# books all contain these and are definitely worth investing in. Or you can read the codeproject articles. The patterns aren't categorised either as you'll see.

The code examples below is generally just the pattern itself (i.e. the classes/interfaces involved in the pattern) and not the types in use. The download link above contains a full solution of all 7 patterns (in Visual Studio 2008 format) with usage, so it's recommended you download this to get a clearer picture.

Click on the code example boxes to expand the source code

Factory

Summary
One class (the factory) creates instances of other classes which all implement the same interface or subclass a specific class. The factory optionally calls the method(s) of the instance it creates.

Example usage
Plugin architecture (implemented alongside reflective loading of types) is one good usage of the Factory design pattern.

Code example


Abstract Factory

Summary
The abstract factory is the base class of all factory classes, but is responsible for creating instances of the classes that are derived from it (via a static method). It goes one step further after this, so each factory also uses another another set of concrete types (specific to itself) based on an abstract class.

Example usage
As the code below illustrates, a common use is for abstracting GUI elements out, so that that each different concrete factory creates components for a different platform, this could be an operating system or device like the web/windows. This is a fairly common example that's found in the Oreilly C# book and on wikipedia.

Code example


Singleton

Summary
A class that only allows one instance of itself, which is accessed via a static property.

Example usage
The commonest example is an application only allowing one instance of itself, much like Windows Media Player does. Another example is a 'global' instance of a class, which contains settings or config information.

Code example

This is Jon Skeet's lazy implementation example. He has a full discussion on the various ways of implementing a singleton in C#, the example below being the final version. The full article can be found here


Strategy

Summary
Multiple classes implement an interface, handling an algorithm in a different way.

Example
Sorting is the clearest working example of the Strategy pattern. In .NET you'll find it in the IComparer interface alongside Array.Sort/LINQ, see the links section for an article on this on MSDN.

Code example


Iterator pattern
Summary
Iterate through a list of items, with an enumerator class ordering the set/list before it is iterated through.

Example
Iterators are built into C# via foreach statements and IEnumerator. The iterator is the foreach statement, which requires the object it is iterating through to implement IEnumerator. The foreach statement calls GetEnumerator on the collection or class you specify. With the introduction of the yield keyword into C# this has been made even simpler.

Code example


Mediator pattern

Summary
This pattern is best illustrated in code as the source describes it a lot more concisely than in prose.

One central class (the mediator) is used by many 'client' classes to send messages with (n.b. 'client' is my own term not one from the original pattern description). A 'client' or several 'client' classes then have a reference to this mediator instance as a private field, and use it to send messages. The mediator has an event which each 'client' subscribes to. This event is fired each time the mediator sends a message.

Example
A chat room could use the Mediator pattern, or a system where many 'clients' each receive a message each time one of the other clients performs an action (for chat rooms, this would be when each person sends a message). In reality using the Mediator pattern for a chat room would only be practical when used with remoting. Using raw sockets wouldn't allow for the delegate callbacks (people subscribed to the Mediator class' MessageReceived event).

Code example


Observer

Summary
Very similar to the Mediator pattern. The only difference is the 'clients', or the Observers as they are now called, don't broadcast via the mediator (now called the Subject). The observers just sit and listen for event(s) being broadcast by the Subject. The subject can be doing anything it likes completely independent of the Observers; the observers as the name implies just observe, they aren't expected to interact with the subject in the pattern.

Example
System messages is one example of the Observer pattern - where lots of Observers sit listening for various different messages. In Java ActionListeners implement a form of the Observer pattern (and Command pattern), in C# the delegate callback system for events makes the Observer pattern transparent with the syntax of the language. You can find examples of this with events in control libraries.

Code example


State

Summary
Like a finite state machine but implemented using a class for each state, rather than an enumeration and/or switch statement.

Example
A basic example would be a traffic light system - GreenState, AmberState, RedState. Each of the classes is expected to implement an IState() interface or subclass a base class which contains the states that can be moved from/to via methods. The pattern lends itself to allowing each class to handle the state it represents in more detail (and a lot easier to read and maintain) than a giant switch statement. The current state (called the Context) is passed to each class in each method.

For games where your current state (context) is important, like (MMO)RPG games, the State pattern could be used. For example some games of this genre require you to have perform one action, say cast a specific spell, before you can perform another spell.

Code example


Facade

Summary
Access multiple classes in one simple to use class. This class is often static too.

Example
A common use of the Facade pattern is with data access managers, a facade class that contains only static methods for CRUD operations. Another example might be a class that handles payment in an online store. This fascade class would link into multiple payment providers (paypal, visa/mastercard) as well as updating any order details in a database table. Rather than making the UI perform 10-20 lines of code, this could be done in a simple CheckoutManager.ProcessPayment(...) method. The minor setback of this of course is handling return codes.

Code example



That's the seven, hopefully it's been some use. I plan to add to the collection in a new article soon, in the meantime here's some brief summaries of ones I've missed out:

Adapter
A good example of the Adapter pattern can be found inside the Framework class library (see the links section below).

Memento
Used for saving the current state of your system, which serialization helps to accomodate. You can find this in games for the "save game" functionality. The pattern can also accomodate 'undo' into it.

Proxy
Access methods,fields etc. of a class via another class - the proxy. A common use for this is Authentication where you have to be authenticated before you are allowed to use the other classes. The proxy can switch the classes it uses internally as they implement an interface.

Command
You will have come accross this pattern before if you have dealt with toolbars UI controls. A control's click event will fire an event which passes just the command name. You have to then switch on the command name and perform the relevant action.

Chain of Responsibility
An elogant way of passing responsibility up down a linked-list like chain of classes, where each class references the next class up the chain. The next class up has more responsibility, or rights than the previous class. So the first might be "viewer", the second "editor", the third "admin".

There's even more my mini-summaries have missed: Template, Visitor, Interpretor, Decorator and Bridge. Wikipedia and the other links have details on these.

Links
Discover the Design Patterns You're Already Using in the .NET Framework
MSDN article about the design patterns you've been using in the .NET framework perhaps without knowing.

Ian Mariano's articles on codeporject.com
A series on design patterns in C#, with UML diagrams and categorised like the gang of four book into creational, behavioural, structural patterns.

Wikipedia
Scroll to the bottom of the page for a list of patterns. Features some clear and concise example source code, mostly in Java.

Design patterns : elements of reusable object-oriented software
The original "gang of four" book, has clear descriptions and UML class diagrams.

C# 3.0 Design patterns
Quite a decent book with UML diagrams of each pattern. A little bit patchy with code examples in places, and the code is far from the FX-cop standards.

Martin Fowler's website
The author of Patterns of Enterprise Application Architecture, another patterns book geared at software for the "enterprise" (not star trek).



› Home
› C#
› Snippets
› Articles
› Tools
› Taglines
› ASP
› Dictionary Object
› FSO
› Unix cheat sheet
› Gaming
› CSS
› Yak
› Umbraco
› About
› Contact
› Privacy
› Projects
› Search
› Sitemap





Buy on Amazon



Buy on Amazon



Buy on Amazon



Buy on Amazon