Six Design Patterns to Start With

One of my colleagues asked me to demonstrate and explain six patterns for folks with little or no exposure to design patterns.  Thou shall count to 6, no more, no less and 8 is right out.  Choosing the six patterns to cover first was actually a bit difficult.  I’m sticking strictly with the original “Gang of Four” patterns initially, because that’s what you’ll bump into the most often.  I scanned over the frequency rating of each pattern listed at www.dofactory.com, but discarded patterns like Observer and Iterator that are tightly integrated into the .Net framework itself.  Singleton is out because it often does more harm than good (I inherited a system that overused singleton’s.  We’re almost done ripping them out).  I’ve got a post in the distant future about a major refactoring I made to StructureMap with a Composite and Visitor pattern combo that did wonders to improve the cyclomatic complexity numbers and unit test coverage, but those are definitely not starter patterns.  In the end I ended up choosing these six to start, partially based on the relevance to work my team is currently doing. 



  1. Template Method
  2. Strategy
  3. Factory Method
  4. Abstract Factory
  5. Facade
  6. Command

If you’ve done any amount of object oriented programming you’ve probably used all of these patterns because they’re just little solutions that constantly reoccur (hence the name “pattern”).  Learning the names of the design patterns and being conscious of pattern usage is effectively an index to a lot of existing writing and design wisdom about prior design pattern usage.  By themselves, the pattern names are valuable as a communication tool with other developers.


Just for fun, I’m going to try to use open source tools for the source of most of the examples.  And for Scott Bellware I’m switching to FrontPage for editing blog posts.  We’ll see how it goes.  When he suggested the switch my gut reaction was “but it will eat my ASP code!”  Some memories just won’t stay down.


Please keep in mind that learning about patterns means more than memorizing pattern names and the mechanics of using the patterns.  Learning the benefits and the drawbacks of patterns is even more important, you can look up the mechanics later.


Template Method


“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. “


Let’s jump right into an example.  You’re building a component that receives and processes incoming messages.  Each type of message is handled and processed differently, but there are some common steps that are always performed in the same order.  In this case you might create a common base class for all of the MessageProcessor classes like the one below to enforce and reuse the basic sequence of actions. 


    public interface IMessageAuditor
    {
        void Audit(string messageType, string userName, 
            string correlationId, string messageBody);
    }
 
 
    public abstract class MessageProcessor
    {
        private readonly IMessageAuditor _auditor;
 
        public MessageProcessor(IMessageAuditor auditor)
        {
            _auditor = auditor;
        }
 
        public void ProcessMessage(Message message)
        {
            IPrincipal principal = Thread.CurrentPrincipal;
            if (this.authorize(message, principal))
            {
                doWork(message);
                audit(message, principal);
            }
        }
 
        // Template Methods that must be overriden by subclasses
        protected abstract string messageType {get;}
        protected abstract bool authorize(Message message, 
            IPrincipal principal);
        protected abstract void doWork(Message message);
 
        private void audit(Message message, IPrincipal principal)
        {
            _auditor.Audit(this.messageType, principal.Identity.Name, 
                message.CorrelationId, message.Body.ToString());
        }
    }
 

In order, each MessageProcessor handles a message by these steps in the ProcessMessage(Message) method:



  1. Get the current IPrincipal containing information about the identity and security rights of the authenticated user
  2. Call the authorize(Message, IPrincipal) method to check for security rights.
  3. If the user is authorized, call the doWork(Message) method to process the message
  4. Call the audit() method that uses the messageType property to create a new audit trail record of the messaging activity

In this case the messageType {get;}, authorize(), and doWork() methods are Template Methods. To create a specific CancelOrderMessageProcessor we merely need to inherit from MessageProcessor and implement these three methods.


    public class CancelOrderMessageProcessor : MessageProcessor
    {
        public CancelOrderMessageProcessor(IMessageAuditor auditor)
             : base(auditor)
        {
        }
 
        protected override string messageType
        {
            get { return “CancelOrder”; }
        }
 
        protected override bool authorize(Message message, IPrincipal principal)
        {
            // go check whether the IPrincipal user is the same user who placed the order
            // referenced by the contents of the message
        }
 
        protected override void doWork(Message message)
        {
            // find the order number and cancel the order in the backend system
        }
    }

So what have we really accomplished here?  For one thing we’ve standardized the message processing.  If we need to handle any new message types we can just create a new subclass and fill in the missing pieces.  Somebody new to the project can create a new message type by following the established pattern.  We’ve also eliminated some code duplication, and that’s always a good thing.


The Template pattern is definitely a double-edged sword.  Used judiciously it eliminates duplication, standardizes the implementation of related classes, and *can* lead to better productivity.  The downside of Template Method’s is the same as inheritance in general.  The workings of a class are split between a super and sub class.  My main warning for the Template Method is to avoid an “Analysis Paralysis” condition where you spend too much time obsessing over the perfect abstractions upfront.   I’ll freely admit that I didn’t completely buy into the XP ideas of simple design and continuous design at first, but I’ve learned that it’s often easier to introduce the superclass/Template Method combinations only after the second or third similar class.  Refactoring tools like ReSharper in conjunction with unit tests make it easier to introduce an abstract super class with its automated “Extract Superclass” refactoring.  In other words, use the Template Method defensively because you don’t have to get it perfect upfront.


Strategy


“Define a family of algorithms, encapsulate each one, and make them interchangeable.”


The Strategy pattern is a widely used way move repeated if/then logic to polymorphism.  Here’s a quick example from a previous job where I worked with supply chain and reverse logistics software for a large manufacturing company.  One of the things you have to account for in your supply chain is the differing means of shipping parts to the manufacturing lines.  Parts to the factory might be supplied by air, truck, or train depending on pricing, availability, and urgency.  There are several places in the code where the logic needs to branch to account for the differing means of shipping to the factory.  Without using a Strategy pattern you might start seeing something like the following switch statement being repeated in your code.


            switch (shippingType)
            {
                case ShippingType.Air:
                    // Air shipping specific logic and functions
                    break;
 
                case ShippingType.Truck:
                    // Trucking specific logic and functions
                    break;
 
                case ShippingType.Train:
                    // Train shipping specific logic and functions
                    break;
 
                default:
                    throw new ArgumentOutOfRangeException(“shippingType”, shippingType, “Unrecognized shipping type!”);
            }

I wouldn’t say that switch statements are inherently evil, but a repeated switch statement on shipping type in different places is evidence of the classic “Switch Statement Smell.”  Repeated switch statements can easily lead to duplicated code, and longish switch statements, in my experience, can lead to code that is hard to read and buggy.  Seeing a repeated switch statement on a type code is a sign that there is an abstraction in your code that’s trying to come out.  Now, let’s say that we went looking for the different times our code switches on shipping type and used this list to define a new interface to represent a new shipping strategy abstraction.


    public interface IShippingStrategy
    {
        DateTime DetermineExpectedArrivalTime(ShippingOrder order);
        Decimal CalculateShippingCost(ShippingOrder order);
        bool IsAvailable(ShippingOrder order);
    }

Next, build out the concrete implementations of IShippingStrategy for air, truck, and train shipping.  Move all specific logic that was in the switch statements into the appropriate Strategy classes.



    public class AirShippingStrategy : IShippingStrategy
    {
    }
 
    public class TruckShippingStrategy : IShippingStrategy
    {
    }
 
    public class TrainShippingStrategy : IShippingStrategy
    {
    }


So, what have we gained?  I’ll claim three advantages over the switch statements:



  1. The code is easier to maintain.  If I need to change the logic for air shipping I only need to go to one place instead of three or more, the AirShippingStrategy class.  The code is easier to read because I’m only looking at the code for air shipping instead of seeing it in the middle of a large switch statement.  The code that calls the new strategy pattern is potentially much easier to read.  The big switch statement can be replaced with a simple call to _currentShippingStrategy.DetermineExpectedArrivalTime(order).  This should make the workflow in the shipping controller code easier to see because its no longer getting bogged down in the specifics of the shipping type.
  2. It’s easier to add new types of shipping.  Instead of modifying code at all the places with a switch statement on shipping type, we just need to do is create a new implementation of IShippingStrategy to add support for new types of shipping to our supply chain automation system.  This is a very common example of the Open/Closed Principle.  With the Strategy pattern in place we can extend the system with new types of shipping without modifying the code that uses the IShippingStrategy interface.  Otherwise, we would have to alter a lot more classes.  More on this topic from David Hayden here.
  3. I’d argue that testing is easier because you can test the specific air, ground, or truck shipping in isolation by just creating the Strategy class instances and exercising the methods.  Without a strategy pattern you would have to test the specific air shipping logic through the calling code that contains the switch statement, creating a more difficult unit test to write and debug.

We have a case like this in our big legacy document messaging system.  The system behaves differently based on what type of document is submitted to the system.  Unfortunately, the code uses repeated switch statements.  This is making it harder for us to map out the differences between the document types because the logical splits are scattered all over the code.  It’s put us into a state where we’re not very confident about our ability to add new document types, which is exactly what we need to do for the business this year.  We will be moving the variation in functionality to a separate handler class for each type of document — even if it’s the last thing I do, at least at work.


The Strategy pattern is very similar to the State pattern, to the point where I abandoned my first idea for an example of a Strategy pattern because I couldn’t decide if it was a strategy or state pattern.  I really wouldn’t waste a lot of energy arguing whether a group of classes are implementing a State or a Strategy pattern.  I think the State pattern is very useful in many cases and often overlooked.  I’ll definitely post on some example usages of the State pattern someday.


Other examples:



  • NHibernate has an abstract class named Dialect that represents a database engine’s particular SQL syntax (because every database’s SQL is every so slightly different).  There is a separate subclass for each type of database engine that is supported by NHibernate (Oracle, MySql, Sql Server, DB2, etc).  New database types can be supported by creating a new subclass of Dialect.
  • Last week I used the ICellHandler interface inside of FitNesse to create a specific handler for DateTime properties inside of FitNesse tests to parse “(today)” and “(today+3)” as valid dates to effectively test date sensitive business rules.  Some day in the near future I’m going to create another implementation to handle .Net enumerations.  That’s always aggravated me, until I finally realized that FitNesse is easy to extend (not that the documentation in FitNesse makes this obvious).

Okay Jeremy, exactly how do you get the different Strategy implementation inside your code?  I distinctly remember getting a question like that from an old Cobol developer several years ago when I was explaining polymorphism and its advantages to him.  On the off chance he’s out there somewhere, one of the more common and simpler possibilities is the Factory pattern.


Factory Method


“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. “


Last year we had to write several “translation” classes to map flat files to an xml format.  One easy way to do this is to create an abstraction that represents the mapping from a flat file column to the xml structure.


    public interface INodeMapping
    {
        void MapColumn(string textValue, XmlNode targetNode);
    }
 
    // Simple implementation of INodeMapping
    public class BasicNodeMapping : INodeMapping
    {
        private readonly string _nodeName;
 
        public BasicNodeMapping(string nodeName)
        {
            _nodeName = nodeName;
        }
 
        public void MapColumn(string textValue, XmlNode targetNode)
        {
            XmlElement newNode = targetNode.OwnerDocument.CreateElement(_nodeName);
            newNode.InnerText = textValue;
            targetNode.AppendChild(newNode);
        }
    }

The actual translation classes aren’t much more that an aggregation of INodeMapping objects.  The superclass for all of the translation classes has an abstract Factory Method (buildMappings() in the code below) to build the specific array of INodeMapping objects for the concrete instance.  I think you can say that the Factory Method is a specific type of Template Method.  Something to keep in mind with patterns is that they often occur in clusters and even in the same class.  Please don’t waste calories arguing or worrying over exactly which pattern a class exhibits.


    public abstract class FlatFileToXmlTranslator
    {
        // Factory Method
        protected abstract INodeMapping[] buildMappings();
    }
 
    public class ReallyWeirdFlatFileFormatTranslator : FlatFileToXmlTranslator
    {
        // Factory method
        protected override INodeMapping[] buildMappings()
        {
            return new INodeMapping[] {
                new BasicNodeMapping(“Name”),
                new BasicNodeMapping(“Address”),
                new BasicNodeMapping(“City”)
                };
        }
    }

Many people, including myself, think of a Factory Method as something different than the GoF definition.  “Factory Method” often describes a class or a method that returns the proper Strategy or State class based on some sort of input.  Going back to the shipping Strategy Pattern example from above, you might use something like the following method to select the proper IShippingStrategy implementation for a given ShippingType.


        // Yes Gary, there are *some* perfectly valid usages for static members
        public static IShippingStrategy SelectShippingStrategy(ShippingType shippingType)
        {    
            switch (shippingType)
            {
                case ShippingType.Air:
                    return new AirShippingStrategy();
 
                case ShippingType.Truck:
                    return new TruckShippingStrategy();
 
                case ShippingType.Train:
                    return new TrainShippingStrategy();
 
                default:
                    throw new ArgumentOutOfRangeException(“shippingType”, shippingType, “Unrecognized shipping type!”);
            }
        }

Abstract Factory


“Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”


The main point in talking about the Abstract Factory is to differentiate it from the Factory Method.  Think of the Abstract Factory as a way to run an application or a piece of code in multiple modes. An easy and common example is the creation of a data access layer to support multiple database engines. When you’re coding against Sql Server you’ll be using the SqlConnection, SqlCommand, and SqlDataAdapter classes.  If you’re using a real database like Oracle you’ll be performing the exact same actions with OracleConnection, OracleCommand, and OracleDataAdapter classes.  What you don’t want to do in this situation is to create a lot of duplicated if/then logic like this:


    public class DataAccessHelper
    {
        private string _connectionString;
        private DatabaseEngineType _databaseEngineType;
 
        public DataAccessHelper(string connectionString, DatabaseEngineType databaseEngineType)
        {
            _connectionString = connectionString;
            _databaseEngineType = databaseEngineType;
        }
 
        // Don’t do it this way
        public int ExecuteSql(string sql)
        {
            IDbConnection connection = null;
            IDbCommand command = null;
 
            if (_databaseEngineType == DatabaseEngineType.SqlServer)
            {
                connection = new SqlConnection();
                command = new SqlCommand();
            }
            else
            {
                connection = new OracleConnection();
                command = new OracleCommand();
            }
 
            // execute the sql with the connection and command objects
        }
 
        // Don’t do it this way
        public IDataReader GetReader(string sql)
        {
            IDbConnection connection = null;
            IDbCommand command = null;
 
            if (_databaseEngineType == DatabaseEngineType.SqlServer)
            {
                connection = new SqlConnection();
                command = new SqlCommand();
            }
            else
            {
                connection = new OracleConnection();
                command = new OracleCommand();
            }
 
            // execute the sql with the connection and command objects
        }

Plus, what if you want to add support later on for DB2 or MySql or PostgresSQL?  One of the consistent themes of design patterns is to eliminate if/then statements and this is no exception.  Here is an actual example of an Abstract Factory class we use in our data access library in a couple of our projects (I might release this as part of StructureMap as an alternative to the data access block in the EntLib someday, but don’t hold your breath).


namespace StructureMap.DataAccess
{
    [PluginFamily("MSSQL")]
    public interface IDatabaseEngine
    {
        IDbConnection GetConnection();
        IDbCommand GetCommand();
        IDbCommand CreateStoredProcedureCommand(string commandText);
        IDbDataAdapter GetDataAdapter();
 
 
        IDataParameter CreateStringParameter(string parameterName, int size, bool isNullable);
        IDataParameter CreateParameter(string parameterName, DbType dbType, bool isNullable);
        string GetParameterName(string logicalName);
    }
}

The Facade (more on this later) class for the data access helper has a dependency on an IDatabaseEngine that is pushed in through constructor injection. 


        [DefaultConstructor]
        public DataSession(IDatabaseEngine database)
            : this(database, 
                   new CommandFactory(database),
                   new AutoCommitExecutionState(database.GetConnection(), database.GetDataAdapter()),
                   new TransactionalExecutionState(database.GetConnection(), database.GetDataAdapter()))
        {
 
        }

Anytime the other classes in the data access layer need an IDbConnection or an IDbCommand they create it through an instance of the IDatabaseEngine interface.  Since we’re primarily a Sql Server shop, the only concrete implementation of IDatabaseEngine is MSSQLDatabaseEngine (partial implementation below), but we could easily use the data access layer against Oracle by creating a different implementation of the IDatabaseEngine interface for Oracle and inject it into the DataSession class.


    [Pluggable("MSSQL")]
    public class MSSQLDatabaseEngine : IDatabaseEngine
    {
        private readonly string _connectionString;
 
        [DefaultConstructor]
        public MSSQLDatabaseEngine(IConnectionStringProvider provider)
        {
            _connectionString = provider.GetConnectionString();
        }
 
        public MSSQLDatabaseEngine(string connectionString)
        {
            _connectionString = connectionString;
        }
 
        public IDbConnection GetConnection()
        {
            return new SqlConnection(_connectionString);
        }
 
        public IDbCommand GetCommand()
        {
            return new SqlCommand();
        }
 
        public IDbDataAdapter GetDataAdapter()
        {
            return new SqlDataAdapter();
        }
 
        
    }

Here’s another example.  Occasionally-connected Smart Clients are a hot topic at the moment.  Say you have a new Smart Client that communicates with three different web services.


    public interface IService1{}
    public interface IService2{}
    public interface IService3{}

The Smart Client is obviously going to behave very differently based on whether or not it is able to connect to the network.  The Abstract Factory might be a very good tool in this case.  Make both a local and remote implementation for each of the three services. 


    public class LocalService1 : IService1{}
    public class LocalService2 : IService2{}
    public class LocalService3 : IService3{}
 
    public class RemoteService1 : IService1{}
    public class RemoteService2 : IService2{}
    public class RemoteService3 : IService3{}

Now, make all other classes get an instance of the three services through an Abstract Factory with this signature.


    public interface IServiceFactory
    {
        IService1 GetService1();
        IService2 GetService2();
        IService3 GetService3();
    }

Next, build two implementations of the IServiceFactory interface.


    public class LocalServiceFactory : IServiceFactory
    {
        public IService1 GetService1()
        {
            return new LocalService1();
        }
 
        public IService2 GetService2()
        {
            return new LocalService2();
        }
 
        public IService3 GetService3()
        {
            return new LocalService3();
        }
    }

 The Smart Client can now completely switch its connection mode by replacing the instance of IServiceFactory between the connected and disconnected modes.


Command


“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue of log requests, and support undoable operations”


Boiling it down, you encapsulate a complex action or transaction into a single class that has a void Execute() method to kick it off.  The command pattern is simple to use, but it has some powerful uses. 



  • Transactions boundaries.  What if you have a long running operation that potentially run several optional database operations that need to run in the same transactions. You really don’t want to keep a database connection open for all the time that you’re evaluating the gating logic on top of the time it takes to do the actual database manipulation.  One answer is to use similar to the Fowler’s Unit of Work pattern where you first you determine what actions to take in the form of an array of command patterns that have some sort of DoOperations(connection, transaction) method that performs its data access commands against the connection and transaction objects that are passed into it.   I’ve always been very leery of declarative transactions for some reason and minus distributed transactions I don’t think declarative transactions are a necessity.
  • Reliable workflow.  Several years ago I got to do a lot of prototyping and brainstorming for a very large manufacturing workflow application that was going to manipulate and interface with a slew of unreliable physical processes and networks.  Wrapping operations inside of command classes that could be persisted can give you a way to queue up operations and create generalized mechanisms to retry operations that fail with network failures.
  • In many cases using a Command pattern can be a great way to break complex code into smaller chunks that are easier to unit test.  Say you have a case where the code is going to do a complex operation with a lot of input, that also requires a lot of logic to decide when to do this complex action.  You end up with one set of tests where you test the command objects, and another set of classes that are solely responsible for creating and configuration of the command classes.

Here’s a typical example of using the Command pattern inside of a user interface to do “CTRL-Z undo’s” of user actions.  Let’s define an interface for that exposes both “do” and “undo” operations for a user interface that’s built around a TreeView motif.


    public interface IClientCommand
    {
        void Do();
        void UnDo();
    }

Now, create an implementation of IClientCommand that removes a child object from a parent object and makes the corresponding change to the TreeView on the screen.  This RemoveChildCommand class will also have ReDo() functionality that will also put the child and child TreeNode back.


    public class RemoveChildCommand : IClientCommand
    {
        private readonly TreeNode _childNode;
        private TreeNode _parentNode;
        private readonly ParentClass _parent;
        private readonly ChildClass _child;
 
        public RemoveChildCommand(TreeNode node, ParentClass parent, ChildClass child)
        {
            _childNode = node;
            _parent = parent;
            _child = child;
        }
 
        public void Do()
        {
            // remove the TreeNode
            _parentNode = _childNode.Parent;
            _childNode.Remove();
 
            // set the Child field of the ParentClass to null
            _parent.RemoveChild(_child);
        }
 
        public void UnDo()
        {
            // add the Child back to the ParentClass
            _parent.AddChild(_child);
 
            // put the TreeNode back
            _parentNode.Nodes.Add(_childNode);
        }
    }

And create a class that will maintain and manage the history of the IClientCommand‘s (apologies for doing this in v1.1 sans generics).  The top menu of the UI application would delegate to the UnDoLast() and ReDoNext() methods.


    public class CommandHistory
    {
        private Stack _pastCommands = new Stack();
        private Stack _futureCommands = new Stack();
 
        public void ExecuteCommand(IClientCommand command)
        {
            command.Do();
            _pastCommands.Push(command);
        }
 
        public void UnDoLast()
        {
            IClientCommand command = (IClientCommand) _pastCommands.Pop();
            command.UnDo();
            _futureCommands.Push(command);
        }
 
        public void ReDoNext()
        {
            IClientCommand command = (IClientCommand) _futureCommands.Pop();
            ExecuteCommand(command);
        }
    }

Facade


“Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. “


The facade is one of the best tools to ensure loose coupling between subsystems by reducing the exposed surface area between subsystems.  It’s exactly what it sounds like, an attractive covering over a complex structure.  Think of a mechanical watch face.  On the outside you see a circle with numbers, an hour hand, and a minute hand.  It’s a pretty simple user interface to use to tell time, but looking behind the watch face you’ll see a complex multitude of gears and springs that do the actual work of telling time. A facade class is the watch face.


Last year my colleague and I built a custom rules engine component that was used inside a much larger messaging system.  Internally, the rules component uses several granular services to:



  1. Translate an industry standard xml message to the internal “canonical” format that the rules engine uses
  2. Load specific information for both the sender and recipient
  3. Locate and build the rule objects for a given recipient and sender
  4. Run the rules against the canonical data model
  5. Process and coordinate any actions that result from the rules, including transaction management

For a variety of reasons, all of these services are coded separately. That’s fine and great for the team building the rules component, but it was potentially confusing for the other team that was consuming the rules component. The simple solution was to create a Facade class to shield the larger application and application team from the internal complexities of the rules component.  This Facade class simply took in an xml document, the id’s of the sender and receiver, and returned an object array of validation errors.


Just because the Facade is in place doesn’t mean that you can’t use the granular services behind the Facade, and we’ve done just that in writing custom testing harnesses.  Theoretically the rules component was built to be used in a different product.  If that ever happens, we’ll probably just create a different Facade appropriate to the new application.


More about the Facade pattern at the original Wiki.


 


More Resources



 

About Jeremy Miller

Jeremy is the Chief Software Architect at Dovetail Software, the coolest ISV in Austin. Jeremy began his IT career writing "Shadow IT" applications to automate his engineering documentation, then wandered into software development because it looked like more fun. Jeremy is the author of the open source StructureMap tool for Dependency Injection with .Net, StoryTeller for supercharged acceptance testing in .Net, and one of the principal developers behind FubuMVC. Jeremy's thoughts on all things software can be found at The Shade Tree Developer at http://codebetter.com/jeremymiller.
This entry was posted in Design Patterns. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Anonymous

    Hi buddy,I like your blog’s design.

  • Anonymous

    Hi buddy,I like your blog’s design.

  • http://www.key-logger.ws keylogger

    it’s very nice is actually a good post………

  • Alberto

    Thanks a lot for your this great introduction to
    desing patterns. Thanks!!!

  • http://www.bakilerparke.com parke

    Thankkk you

  • David

    Your example of the factory method is what a lot of other posts miss. Factory Method is just template method applied to object creation. What that really means it that, similar to the template method, factory method is the creator and sole user of the objects it creates.

    The next example where you show what we now consider factories is dangerous ground. A lot of people will take that example, make it non-static, and then say it’s a factory. To me, a non-static version of that code is an abstract factory. It may an abstract factory of only one product/class, but it is an abstract factory none-the-less.

    The real difference between factory method (key word ‘method’) and abstract factory is that factory method is both the creator and consumer of some product class (hence the templating), whereas abstract factory is a seperate class that the client uses/is injected with, which returns some product.

    I think this point is worth mentioning considering the confusion created by many who call a seperate class “factory pattern”.

  • http://blogs.msdn.com/gblock Glenn Block

    Nice Post. I recommend adding adapter to your pool. Adapter can be extremely powerful especially in integration scenarios with legacy code.

  • http://www.eranachum.com Eran Nachum

    Hello!
    Very informative post, you give here the basics of these patterns which is good. I liked the explanations and examples, helped me understand better the patterns.

    I invite you to take a look in my weblog as well at http://www.eranachum.com

  • Sean

    Hi Jeremy,
    I was looking for a example exactly same like you explained in “Abstract Factory” section(Getting DB connecton of multiple databases) in java.Could you point me to a example where I can find the same thing.

    Thanks
    Sean

  • Sean

    Hi Jeremy,
    I was looking for a example exactly same like you explained in “Abstract Factory” section(Getting DB connecton of multiple databases) in java.Could you point me to a example where I can find the same thing.

    Thanks
    Sean

  • http://www.keithrull.com Keith Rull

    Nice examples! long article but really informative. you got me stuck on my screen reading and analyzing your samples.

    cool stuff!

  • jmiller

    Steve,

    I think that would be a great post for you to write;)

    Jeremy

  • http://codebetter.com/blogs/steve.hebert shebert

    Nice post.

    Here’s a thought to wrap up the discussion and might change the selection of patterns.

    When teaching patterns, I’ve found it useful to describe the inter-relationships between patterns and how to identify them. To me, this is the difference between identifying patterns and knowing how to apply them.

    For example, I’d start with the ‘Command’ pattern and then expand it to the idea of organizing the command objects into a ‘Composite’ pattern. And then, as a final piece, organize the runtime configuration of the ‘Composite’ object using a ‘Builder’ Pattern.

    This gives the opportunity to explore other tools in the GoF book (i.e. Design Pattern Relationships, back cover). With this combination, you can also discuss how patterns are organized (Creational/Structural/Behavioral).

    I personally think the Design Pattern Relationships diagram is the least understand and yet most valuable tool in the book.

    -Steve

  • http://davidhayden.com/blog/dave/ dhayden

    Great post, Jeremy. Adding the dependency injection to many of the examples introduces a twist to the topic in a rather unique and good way.

    It would be interesting to add where you can find these patterns in the .NET Framework. As I just realized the other day, the DbProviderFactory is a great example of the Abstract Factory Pattern and works similar to your excellent example above.

  • jmiller

    Ok, I’ll buy that. I would usually just say the superclass/subclass is a template in general.

  • Christoffer Lette

    First of all, I’d like to say what the others are saying: Nice work! :-)

    Here’s a quote from the GoF’s Design Patterns:

    “We call OpenDocument a template method. A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior.”

    In their example, OpenDocument does what ProcessMessage does in your example. My (their?) point is that the algorithm is the template, not the individual steps.

    Also from the book, in the “Participants” section:

    “AbstractClass – implements a template method defining the skeleton of an algorithm.”

    and

    “ConcreteClass – implements the primitive operations to carry out subclass-specific steps of the algorith.”

    Have I elaborated enough?

  • http://http//weblogs.asp.net/firoz firoz

    Great Tutorial!

  • jmiller

    Christoffer,

    “overrides to some of the steps in the template” – That sounds like a template method to me. The algorithm of ProcessMessage is set, check security, do some work, and audit. The details of those steps are deferred to the subclasses.

    Can you elaborate a bit more?

  • Christoffer Lette

    Since one of my favourite refactorings happen to be “Form Template Method”, I just have to point out that your definition of the actual template method does not correspond to neither the GoF’s nor Fowler’s.

    In your case the template method itself ought to be ProcessMessage in the abstract class. Hence, the messageType {get;}, authorize(), and doWork() methods are *not* template methods. They latters are only overrides to some of the steps in the template.

  • http://www.developernotes.com Nick Parker

    Nice work, I would also point out that the template pattern example is leading into the decorator pattern (although it isn’t fully a decorator in it’s current state). I am looking forward to your post on factoring out singletons.