Wednesday, April 14, 2010

Command Design Pattern By Example in C#

This is part of a series of posts in which we will deal with some of the popular design patters using simple but non-trivial examples.

Command
is probably the most simple of design patterns. All it takes is one Interface with one method.


In this example we will implement a simple but non trivial example using the Command pattern. You can find the link to download the sample at the bottom. It deals with a couple of common validation scenarios.

Here we have an interface called IValidatable with a method called IsValid. So any class which inplements this interface needs to provide functionality for the IsValid method. In our example the Person class and the Address class implement this interface.

And we are able to call person.IsValid and address.IsValid to check for validation.

This also brings us all the advantages of multiple classes implementing the same Interface. For example we can have a List of IValidatable objects and call the IsValid method on iteration.

Please note that even though it is more common to use only one method in this pattern.  It is not necessarily a strict rule.  You can add more methods.  For example we could have included an additional method called GetErrorMessages in IValidatable and called it if IsValid returned false.

Download Sample Code

Happy Coding

Ravi