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 applying them to a real project can be more challenging.
What matters most is not memorizing the exact pattern names or implementing them exactly as described in the documentation; what is more important is understanding the motivation behind each pattern—patterns arise from these motivations.
A good way to better understand the motivations behind these patterns is to study them in a real project. That is the goal of this article: we will explore the source code of an open-source project that makes extensive use of them.
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 explore some of the GoF design patterns used by RoR.
Singleton
The Singleton is one of the most popular and widely used design patterns. 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 behind factories; their purpose is simple: to 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 look at a scenario in which RoR uses it:
- RoR uses the graphics engine OGRE, which needs to instantiate classes of the ParticleEmitter kind.
- RoR defines its own ParticleEmitter class, named BoxEmitter, which inherits from ParticleEmitter, and it needs 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 and use this new BoxEmitter class from RoR? This is where the “Factory Method” pattern comes in:
OGRE has an abstract class named ParticleEmitterFactory that provides the CreateEmitter method. To do its job, OGRE needs a concrete factory. RoR defines a new factory, BoxEmitterFactory, inheriting from ParticleEmitterFactory, and overrides the CreateEmitter method.
RoR provides this factory to OGRE using ParticleSystemManager::addEmitterFactory(ParticleEmitterFactory *factory). Each time OGRE needs an instance of ParticleEmitter, 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 useful for isolating instantiation logic and improving cohesion, but the “Factory Method” pattern is better suited when low coupling is also required.
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 the algorithm’s structure remains unchanged while subclasses provide parts of the implementation.

Let’s use CQLinq to detect all the classes using the template method pattern. To do this, 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 such class. It needs to process received IRC events, so it overrides the processIRCEvent method to implement its specific behavior.
With this pattern, we can easily change an algorithm’s implementation without changing its skeleton. It reduces boilerplate code and makes these classes easier to maintain.
It also enforces the low coupling, because the client can reference only the abstract class instead of the concrete ones.
Strategy
There are many situations in which classes differ only in their behavior. In such cases, it is a good idea to isolate the algorithms in separate classes so that different algorithms can be selected 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 can have multiple behaviors—fixed, free, static, or isometric—and its behavior can be changed dynamically. Additional behaviors can also be added in the future.
CameraManager uses the abstract IBehavior class. Here are all the CameraManager methods that use IBehavior.

As we can see, there is a method named switchBehavior that changes 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.
However, their goals are 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 transition from one state to another to achieve the final objective, so there is a relationship between the different states.
Here are all the state classes inheriting from the abstract class AppState.

As with the Strategy pattern, the other classes reference only the abstract class. Here are all the methods that use AppState.

As we can see, AppStateManager contains several methods for managing 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. A simple way to identify the facades being used is to search for external code referenced by the project.
Here are all the namespaces used by the RoR project:

Let’s take the Caelum namespace as an example and search for RoR classes that use it.
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 that is tightly coupled to our code—i.e., many classes use the library directly—it will be very difficult to replace it. 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 is useful to understand the motivations for using them in your code. Exploring how patterns are implemented in well-known open-source projects can help you better understand their value.
