Past October, I participated in an ALT.NET Hispano VAN about Design Patterns. I presented some of the classic design patterns of the GangOfFour book. My presentation (Spanish) DesignPatterns.pptx The VAN video (Spanish voice) and resources.
During the VAN, I explain and use some of the design patterns, but with a key idea: use all of them in the same example: an interpreter. You can download the C# code from my Google Code Project AjCodeKatas at Patterns folder.
Maybe, that code evolve, but you can download the VAN original code from Patterns20101017.zip.
Note: the namespaces that I used are related to the patterns. The code was developed using TDD (Test-Driven Design).
This is the list of patterns:
Interpreter: used in a expression interpreted, base of all the example.
Composite: with commands in the interpreter. There is a composite comamnd that contains a list of commands.
Template Method: it is in the method .Evaluate of the BinaryExpression: it evaluated two expressions and the results is used in the method .Apply, that is implemented at each of the subclasses.
Strategy: Instead of writing a class, I use Func<obj,obj,obj> to apply in the evaluation of ArithmeticBinaryExpression.
Decorator: An IContext is passed to each command and expressiona. It has the responsability of keep the values of the variables. I decorated it to have a new IContext implementation that raise events with info about what variables and values are read and changed.
Observer: Events in .NET, an evolution of the original pattern.
Adapter: I want to consume a file with code of the language to interpret, using a TextReader. But I need to read words, tokens (see Token class). Lexer class is an adapter around the TextReader. It has new method to read the next token in the stream.
Abstract Factory: The example is not in the interpreter. There is code that use ADO.NET providers, that act as an abstract factory.
Facade: with Strategy, it’s one of the most important pattern to learn and employ. All Strategy derives to composition instead inheritance, and to Dependency Injection, Inversion of Control and IoC containers. For me, Facade is like the “API” of our business, domain. A classic example: ISession in NHibernate.
Machine class is a kind of Facade. It is the entry point to the interpreter. It coordinate and delegate work to Parser (another adapter example), Lexer, files, Context. The interpreter consumer can invoke this object without direct interaction with the internal implementation.
Visitor: I wrote a class, that takes an instance of the Interpreter (as a tree to execute) and decompiles it to text.
You have more examples and UML diagrams at:
Thanks to the ALT.NET Hispano for the opportunity to talk about this topic. I should publish more advances of my series about writing an interpreter using TDD.