The majority of developers have already heard about design patterns; the GOF (Gang Of Four) patterns are the most popularized, and each developer has their own way to learn them. We can name:
- Reading a book.
- From web sites.
- From a colleague.
- Taking a training course.
Regardless of the method chosen, we can learn the patterns by heart and spend hours memorizing their UML diagrams, but sometimes, when we need to use them in a real project, it becomes more problematic.
What’s very important is not to know exactly the pattern names and how to implement them as described in the documentation; what’s more relevant is the motivation behind each pattern — it’s from motivations that we invent patterns.
To better master the pattern motivations, an alternative way is to study them in a real project. That’s the goal of this article: we will explore the source code of an open source project that uses them heavily.
Analysis of Rigs of Rods
Rigs of Rods (“RoR”) is an open source multi-simulation game which uses soft-body physics to simulate the motion and deformation of vehicles. The game is built using a specific soft-body physics engine called Beam, which simulates a network of interconnected nodes (forming the chassis and the wheels) and gives the ability to simulate deformable objects. With this engine, vehicles and their loads flex and deform as stresses are applied. Crashing into walls or terrain can permanently deform a vehicle.

Let’s go discover some GOF design patterns used by RoR.
Singleton
The singleton is the most popular and the most used one. RoR uses a generic singleton to avoid repeating the same code for each singleton class; it defines two variants: a singleton that creates a new instance and another where an already created instance is assigned.

Let’s search for all the RoR singletons, for that we can use CQLinq:
from t in Types where t.DeriveFrom(“RoRSingletonNoCreation“) || t.DeriveFrom(“RoRSingleton“)
select t
Motivation:Let’s take the example of the InputEngine singleton: RoR needs to store data about the keyboard, mouse, and joysticks, which are detected at initialization by the InputEngine class. Many classes need the same input device data, and there’s no need to create more than one instance, so the primary motivation is to “Create one instance of the InputEngine class“.
However, using the singleton has become controversial, and not all architects and designers recommend it; here’s an article about the singleton controversy.
Factory Method
There is no mystery about factories; their goal is simple: create instances. A simple factory containing a CreateInstance method could achieve this goal. However, RoR uses the Factory Method pattern for all its factories instead of a simple factory.
Motivation:To better understand this pattern, let’s describe the scenario where RoR uses it:
- RoR uses the graphics engine OGRE, which needs to instantiate classes of the ParticleEmitter kind.
- RoR defines and uses its specific ParticleEmitter class named BoxEmitter, which inherits from it, and wants OGRE to use this new class as a ParticleEmitter.
- OGRE doesn’t know anything about RoR.
The question is: how will OGRE know how to instantiate this new BoxEmitter class from RoR and use it? Here comes the role of the “Factory Method” pattern:
OGRE has an abstract class named ParticleEmitterFactory which has the CreateEmitter method, and to do its job, OGRE needs a concrete factory. RoR defines a new factory, BoxEmitterFactory, inheriting from ParticleEmitterFactory, and overrides the CreateEmitter method.
RoR gives this factory to OGRE using ParticleSystemManager::addEmitterFactory(ParticleEmitterFactory *factory). And each time OGRE needs an instance of ParticleEmitter, the BoxEmitterFactory is invoked to create it.
The most important motivation is the low coupling; indeed, OGRE doesn’t know anything about RoR and yet it can instantiate classes from it.
Another motivation is to enforce the cohesion by delegating the instantiation to a specific factory class.
Using a simple factory is interesting to isolate the instantiation logic and enforce cohesion, but using the “Factory Method” pattern is more suitable to also enforce low coupling.
Template Method
The template method defines the skeleton of an algorithm in a method, deferring some steps to subclasses. The template method lets subclasses redefine some steps of an algorithm without changing the algorithm’s structure.
The objective is to ensure that algorithm’s structure stays unchanged, while subclasses provide some part of the implementation.

Let’s use CQLinq to detect all the classes using the template method pattern. For that, we can search for abstract classes (the Abstract class from the UML diagram below) having one or more methods (templateMethod() from the diagram) which use some methods implemented in the subclass (primitive1 and primitive2 from the diagram).
from t in Types where t.IsAbstract && t.Methods.Where(a=> a.NbLinesOfCode>0 && a.MethodsCalled.Where(b=>b.IsPureVirtual && b.ParentType==t).Count()>0).Count()>0 select t
Motivation:Let’s take the IRCWrapper class as an example; its “process” method contains the logic for processing received IRC events. Here are the methods called by it:

It invokes the pure virtual method processIRCEvent, which must be implemented by an IRCWrapper derived class. LobbyGui is one of them and needs to process the received IRC events; it overrides the processIRCEvent method to implement its specific behavior.
With this pattern, we can easily change the implementation of algorithms without changing the skeleton; it removes the boilerplate code and makes the maintenance of these classes easy.
It also enforces the low coupling, because the client can reference only the abstract class instead of the concrete ones.
Strategy
There are common situations where classes differ only in their behavior. For these cases, it’s a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.
Let’s use CQLinq to detect all classes using the strategy pattern. For this purpose, we can search for abstract classes having multiple derived classes, where the client references the abstract class instead of the concrete implementations.
from t in Types where t.IsAbstract && t.DirectDerivedTypes.Count()>1 !t.IsThirdParty
let tt=t.DirectDerivedTypes
from db in tt where db.Methods.Where(a=>a.NbMethodsCallingMe!=0 !a.IsStatic).Count()==0
select new {db,t}
Motivation:The camera could have multiple behaviors: fixed, free, static or isometric, and this behavior could be changed dynamically. Also, other behaviors could be added in the future.
The CameraManager uses the abstract behavior IBehavior; here are all the methods from CameraManager using the IBehavior class.

As we can observe, there is a method named switchBehavior to change the behavior dynamically.
This pattern enforces the low coupling — indeed, CameraManager doesn’t know the concrete behaviors — and also enforces the high cohesion, because each specific behavior is implemented in an isolated class.
State
The State pattern is similar to the Strategy design pattern from an architectural point of view, and for this reason, with the previous CQLinq query where we searched for the strategy pattern, we also found state classes.
But the goal is different: the Strategy pattern represents an algorithm that uses one or more IStrategy implementations. There’s no correlation between these different behaviors; however, with the State pattern we pass from one state to another to achieve the final objective, so there’s cohesion between the different states.
Here are all the state classes inheriting from the abstract class AppState.

Like the Strategy pattern, only the abstract class is referenced by the other classes; here are all the methods using AppState.

As we can observe, AppStateManager contains many methods to manage the state lifecycle.
Motivation:
Like the Strategy pattern, this pattern enforces the low coupling — AppStateManager doesn’t know the concrete states — and also enforces the high cohesion, because each operation is isolated in its corresponding state.
Facade
A facade is an object that provides a simplified interface to a larger body of code, such as a class library. And to detect the facades used, the simple way is to search for external code used.
Here are all the namespaces used by the RoR project:

Let’s take the Caelum namespace as an example and search for classes using it from RoR.
from m in Methods where m.IsUsing (“Caelum“)
select new { m }
Only SkyManager uses the Caelum namespace directly, so it represents the Caelum facade.
Motivation
If we use an external library and it’s highly coupled with our code — i.e. many classes use this library directly — it will be very difficult to change this external library. However, if a facade is used, only its implementation will have to change if we want to replace the external library.
This pattern enforces the low coupling with external libraries.
Conclusion
After learning the GOF patterns, it’s interesting to know the motivations behind using them in your code. Discovering the implementation of patterns from well-known open source projects could help you better understand the utility of the patterns.
