sloppycode.net
Software Design Patterns in C#
Common software design patterns in C#.
Home
›
Articles
›
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
namespace DesignPatterns { ///
/// Defines the methods/properties the plugin can support. ///
public interface IPlugin { string GetDetails(); } ///
/// A plugin for Gifs. ///
public class GifHandler : IPlugin { public string GetDetails() { return "I'm a plugin for .GIF filetypes"; } } ///
/// A plugin for jpgs. ///
public class JpgHandler : IPlugin { public string GetDetails() { return "I'm a plugin for .JPG filetypes."; } } ///
/// The class to handle extensions with. ///
public class PluginFactory { public string ShowFileDetails(string extension) { IPlugin plugin = null; switch (extension) { case "gif": plugin = new GifHandler(); break; case "jpg": plugin = new JpgHandler(); break; default: throw new NotSupportedException(string.Format("{0} is not supported.", extension)); } return plugin.GetDetails(); } } }
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
namespace DesignPatterns { public abstract class AbstractPluginFactory { public static AbstractPluginFactory GetFactory(string renderer) { switch (renderer) { case "ASPX": return new ASPXRendererFactory(); case "Winforms": return new WinformsRendererFactory(); default: throw new NotSupportedException(string.Format("{0} is not supported", renderer)); } } public abstract Renderer Renderer { get; } } public class ASPXRendererFactory : AbstractPluginFactory { private Renderer _renderer; public override Renderer Renderer { get { return _renderer; } } public ASPXRendererFactory() { // This could be a protected field in PluginFactory _renderer = new ASPXRenderer(); } } public class WinformsRendererFactory : AbstractPluginFactory { private Renderer _renderer; public override Renderer Renderer { get { return _renderer; } } public WinformsRendererFactory() { // This could be a protected field in PluginFactory _renderer = new WinformsRenderer(); } } public abstract class Renderer { public abstract void DrawImage(string filename); } public class WinformsRenderer : Renderer { public override void DrawImage(string filename) { // This would draw onto a canvas provided via // a Graphics object. Console.WriteLine("Drawing an image for Windows forms"); } } public class ASPXRenderer : Renderer { public override void DrawImage(string filename) { // This would output an
tag to the child controls or similar. Console.WriteLine("Drawing an image for ASP.NET"); } } }
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
public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }
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
namespace DesignPatterns { public class User { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return string.Format("{0} {1}", Name, Age); } } ///
/// Compares two users based on name. ///
public class NameSorter : IComparer
{ public int Compare(User x, User y) { return x.Name.CompareTo(y.Name); } } ///
/// Compares two Users based on their age. ///
public class AgeSorter : IComparer
{ public int Compare(User x, User y) { return x.Age.CompareTo(y.Age); } } ///
/// A simple extension method class for pretty-printing the /// List
collection. ///
public static class ListExtension { public static string Print(this List
list) { StringBuilder builder = new StringBuilder(); foreach (User user in list) { builder.AppendLine(user.ToString()); } return builder.ToString(); } } }
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
namespace DesignPatterns { private static void IteratorTest() { IteratorExample example = new IteratorExample(); foreach (string item in example) { Console.WriteLine(item); } } public class IteratorExample : IEnumerable { Dictionary
_dictionary; public IteratorExample() { // Add 5 names to a key/value pair list. _dictionary = new Dictionary
(); _dictionary.Add("Hans", "Pisces"); _dictionary.Add("Fred", "Aquarius"); _dictionary.Add("Andrew", "Gemini"); _dictionary.Add("Zach", "Scorpio"); _dictionary.Add("Berfa", "Cancer"); } ///
/// Demonstrates yield with IEnumerable. ///
public IEnumerator GetEnumerator() { // Sort by name var sorted = from d in _dictionary orderby d.Key select d; // Iterate through the sorted collection foreach (KeyValuePair
item in sorted) { yield return item.Key; yield return string.Format("({0})",item.Value); } } } }
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
namespace DesignPatterns { public delegate void MessageReceivedEventHandler(string message,string from); public class Mediator { public event MessageReceivedEventHandler MessageReceived; public void Send(string message, string from) { if (MessageReceived != null) { Console.WriteLine("Sending '{0}' from {1}",message,from); MessageReceived(message, from); } } } public class Person { private Mediator _mediator; public string Name { get; set; } public Person(Mediator mediator,string name) { Name = name; _mediator = mediator; _mediator.MessageReceived += new MessageReceivedEventHandler(Receive); } private void Receive(string message, string from) { if ( from != Name ) Console.WriteLine("{0} received '{1}' from {2}",Name,message,from); } public void Send(string message) { _mediator.Send(message, Name); } } }
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
namespace DesignPatterns { ///
/// The use of an interface here mightseem a bit redundent, but it's to keep /// inline with the original gang of 4 definition of the pattern. The implementing class /// is still responsible for wiring itself to the Subject's notify event. ///
public interface IObserver { void Update(string message); } public class Observer { ///
/// A friendly name for the Observer. ///
public string Name { get; set; } ///
/// Filters messages starting with the string provided. ///
public string MessageFilter { get; set; } ///
/// Creates a new instance of an Observer. ///
///
The class that broadcasts/notifies us of its actions. ///
A friendly name for the observer. public Observer(Subject subject,string name) { Name = name; subject.Notify += new Action
(Update); } ///
/// Called each time the Subject notifies this Observer. ///
///
private void Update(string message) { // Filter the message? if (!string.IsNullOrEmpty(MessageFilter)) { if ( message.StartsWith(MessageFilter) ) Console.WriteLine("{0} received the message {1}", Name, message); } else { Console.WriteLine("{0} received the message {1}", Name, message); } } } ///
/// This is the class that would perform all or any tasks and then inform /// each subscribed Observer when it has down this. ///
public class Subject { ///
/// Tradionalists might want this to use a delegate called *EventHandler /// but I'm being lazy and using the Generic Action
delegate. ///
public event Action
Notify; public void Run() { Thread thread = new Thread(new ThreadStart(InternalRun)); thread.Start(); } ///
/// A small mockup to simulate doing some work. ///
private void InternalRun() { string message; // 5 basic messages, sleeping between them to simulate // intensive IO operations or calculations. message = "Calculating Pi to 2000 dp."; OnNotify(message); Thread.Sleep(2000); message = "Copying an item over the network using Vista pre-SP1"; OnNotify(message); Thread.Sleep(2000); message = "Finding all files that end in *.dll"; OnNotify(message); Thread.Sleep(2000); message = "Formatting a floppy."; OnNotify(message); Thread.Sleep(2000); message = "Spidering google."; OnNotify(message); Thread.Sleep(2000); } ///
/// Send out a notification to all Observers. ///
protected virtual void OnNotify(string message) { if (Notify != null) Notify(message); } } }
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
namespace DesignPatterns { ///
/// Default State that every state inherits from. ///
public abstract class State { ///
/// Holds the current state we're in. ///
public State CurrentState { get; set; } public virtual string SitDown(State context) { return ""; } public virtual string Walk(State context) { return ""; } public virtual string Run(State context) { return ""; } } public class SittingState : State { public override string SitDown(State context) { context.CurrentState = new SittingState(); return "Sitting down."; } public override string Walk(State context) { context.CurrentState = new WalkingState(); return "I'm walking."; } public override string Run(State context) { return "I can't run while I'm sitting down."; } } // (WalkingState and RunningState classes have been cut out, see the download) }
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
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