
{"id":720,"date":"2016-03-13T16:41:23","date_gmt":"2016-03-13T16:41:23","guid":{"rendered":"http:\/\/www.codergears.com\/Blog\/?p=720"},"modified":"2016-06-07T15:23:42","modified_gmt":"2016-06-07T15:23:42","slug":"learn-design-patterns-from-real-projects-rigsofrods-case-study","status":"publish","type":"post","link":"https:\/\/codergears.com\/Blog\/?p=720","title":{"rendered":"Learn design patterns from real projects: RigsOfRods case study."},"content":{"rendered":"<p style=\"color: #555555;\">The majority of developers have already heard about the design patterns,\u00a0<a style=\"color: #2970a6;\" href=\"http:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">GOF(Gang Of Four)<\/a>\u00a0patterns are the most popularized, and each developer has his way to learn them , we can enumerate:<\/p>\n<ul style=\"color: #555555;\">\n<li>Reading a book.<\/li>\n<li>From web sites.<\/li>\n<li>From a collegue.<\/li>\n<li>Doing a training.<\/li>\n<\/ul>\n<p style=\"color: #555555;\"><span id=\"more-741\"><\/span>Regardless of the method chose, we can learn by heart the patterns and spent hours to memorize their UML diagrams, but sometimes when we need to use them in a real project, it becomes more problematic.<!--more--><\/p>\n<p><span style=\"color: #555555;\">What&#8217;s very important is not to know exactly pattern names and how to implement them as described in the documentation, but what&#8217;s more relevant is the motivation\u00a0behind each pattern,\u00a0it&#8217;s from motivations that we invent the patterns.<\/span><\/p>\n<p><span style=\"color: #555555;\">To master better pattern motivations, an alternative way is to study them from a real project. It&#8217;s the goal of this article, we will try to discover an open source project using them heavily.<\/span><\/p>\n<p style=\"color: #555555;\"><strong>Analysis of Rigs of Rods<\/strong><\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/www.rigsofrods.com\/content\/\">Rigs of Rods (\u201cRoR\u201d)<\/a>\u00a0is 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.<\/p>\n<p style=\"color: #555555;\">Here we go to dicover some GOF design patterns used by RoR.<\/p>\n<p style=\"color: #555555;\"><strong>Singleton<\/strong><\/p>\n<p style=\"color: #555555;\">The singleton is the most popular and the most used one. RoR uses generic singleton to avoid repeating the same code for each singleton class, and define two variants: a singleton that create new\u00a0instance and another where the instance is assigned.<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror7.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-753\" title=\"ror7\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror7.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">Let\u2019s search for all RoR singletons, for that we use <a href=\"http:\/\/cppdepend.com\/cqlinq.aspx\">CQLinq<\/a>:<\/p>\n<p style=\"color: #555555;\"><span style=\"color: #3366ff;\">from<\/span>\u00a0t\u00a0<span style=\"color: #3366ff;\">in<\/span>\u00a0Types\u00a0<span style=\"color: #3366ff;\">where<\/span>\u00a0t.DeriveFrom(\u201c<span style=\"color: #ff6666;\">RoRSingletonNoCreation<\/span>\u201c) || t.DeriveFrom(\u201c<span style=\"color: #ff6666;\">RoRSingleton<\/span>\u201c)<br \/>\n<span style=\"color: #3366ff;\">select<\/span>\u00a0t<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror211.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-802\" title=\"ror21\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror211.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\"><em>Motivation:<\/em><\/p>\n<p style=\"color: #555555;\"><span style=\"color: #555555;\">Let&#8217;s take the example of the InputEngine singleton, RoR needs to store information about keyboard, mouse, and joysticks, which are detected in the initialisation by the InputEngine class, all classes needs the same data of the input devices, and no need to create more than one instance, so the primary motivation is to <strong>\u201cCreate one instance of InputEngine class\u201c<\/strong>.<\/span><\/p>\n<p style=\"color: #555555;\">However using singleton became controversial, and not all architects and designers recommend it, here\u2019s an\u00a0<a style=\"color: #2970a6;\" href=\"http:\/\/code.google.com\/p\/google-singleton-detector\/wiki\/WhySingletonsAreControversial\">article<\/a>\u00a0talking about the singleton controversy.<\/p>\n<p style=\"color: #555555;\"><strong>Factory Method<\/strong><\/p>\n<p style=\"color: #555555;\"><span style=\"color: #555555;\">There is no mystery about factories, their goal is simple:\u00a0Create instances, and a simple factory containing a CreateInstance method could achieve this goal. However, RoR uses the Factory Method pattern for all its factories instead of using a simple factory.<\/span><\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror5.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-751\" title=\"ror5\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror5.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\"><em>Motivation:<\/em><\/p>\n<p style=\"color: #555555;\">To understand better this pattern let\u2019s describe the scenario where RoR uses this pattern:<\/p>\n<ul>\n<li><span style=\"color: #555555;\">RoR uses the graphics engine\u00a0<\/span><a style=\"color: #2970a6;\" href=\"http:\/\/www.ogre3d.org\/\">OGRE<\/a><span style=\"color: #555555;\">, which\u00a0needs to instantiate classes of kind ParticleEmitter class.<\/span><\/li>\n<li><span style=\"color: #555555;\">RoR defines and uses its specific ParticleEmitter\u00a0class named BoxEmitter which\u00a0inherits from it, and wants that OGRE uses this new class as ParticleEmitter.<\/span><\/li>\n<li><span style=\"color: #555555;\">OGRE doesn\u2019t know anything about RoR.<\/span><\/li>\n<\/ul>\n<p style=\"color: #555555;\">The question is how OGRE will know how to instantiate this new class BowEmitter from RoR and uses it?\u00a0Here come the role of \u201cFactory Method\u201d pattern:<\/p>\n<p style=\"color: #555555;\">OGRE has an abstract class ParticleEmitterFactory which has the CreateEmitter method, and to acheive his job , OGRE needs to a concrete factory, RoR defines a new factory BoxEmitterFactory inheriting from ParticleEmitterFactory and overloads CreateEmitter method.<\/p>\n<p style=\"color: #555555;\">RoR gives to OGRE this factory using ParticleSystemManager::addEmitterFactory (ParticleEmitterFactory * factory). And each time OGRE needs an instance of ParticleEmitter, the BoxEmitterFactory is invoked to create it.<\/p>\n<p style=\"color: #555555;\">The most important motivation is the\u00a0<strong>low coupling<\/strong>, indeed OGRE doesnt know anything about RoR and it can instatiate classes from it.<\/p>\n<p style=\"color: #555555;\">Another motivation is to enforces the <strong>cohesion<\/strong>, and delegate the instantiation to a specific calss.<\/p>\n<p style=\"color: #555555;\">Using a simple factory is interesting to isolate the logic instantiation and enforces the cohesion , but using \u201cFactory Method\u201d is more suitable to alse enforces low coupling.<\/p>\n<p style=\"color: #555555;\"><strong>Template Method<\/strong><\/p>\n<p style=\"color: #555555;\">Template method defines the skeleton of Algorithm in a method, differing some steps to subclasses. Template method lets subclasses redefine some steps of an algorithm without changing the algorithm\u2019s structure.<\/p>\n<p style=\"color: #555555;\">The objective is to ensure that algorithm\u2019s structure stays unchanged, while subclasses provide some part of implementation.<\/p>\n<p style=\"color: #555555;\"><span style=\"color: #555555;\">Let&#8217;s use <a href=\"http:\/\/cppdepend.com\/cqlinq.aspx\">CQLinq<\/a> to detect all classes using template method pattern, For that we can search for methods in a parent class using\u00a0pure virtual methods, and has subclasses implementing these virtual methods.<\/span><\/p>\n<p style=\"color: #555555;\"><span style=\"color: #3366ff;\">from<\/span>\u00a0t\u00a0<span style=\"color: #3366ff;\">in<\/span>\u00a0Types\u00a0<span style=\"color: #3366ff;\">where<\/span>\u00a0t.IsAbstract &amp;&amp;\u00a0<span class=\"skimlinks-unlinked\">t.Methods.Where(a<\/span>=&gt; a.NbLinesOfCode&gt;0 &amp;&amp;<span class=\"skimlinks-unlinked\">a.MethodsCalled.Where(b=&gt;b.IsPureVirtual<\/span>\u00a0b.ParentType==t).Count()&gt;0).Count()&gt;0\u00a0<span style=\"color: #3366ff;\">select<\/span>\u00a0t<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror3.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-747\" title=\"ror3\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror3.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\"><em>Motivation:<\/em><\/p>\n<p style=\"color: #555555;\">Let\u2019s take as example the IRCWrapper class, \u00a0its\u00a0method &#8220;process&#8221; contains the\u00a0logic of processing IRC events received, here are the methods called by it:<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror15.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-791\" title=\"ror15\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror15.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">It invokes the pure virtual method processIRCEvent, which must be implemented by a an IRCWrapper derived class. LobbyGui is one of them and needs to treat the IRC events received, it\u00a0overload the processIRCEvent method to impelments its specific behavior.<\/p>\n<p style=\"color: #555555;\">With this pattern, we can easilly change the implementation of algorithms without changing the skelton, it removes the boilerplate\u00a0code and make easy the maintenance of these classes.<\/p>\n<p style=\"color: #555555;\">It also enforces the\u00a0<strong>low coupling<\/strong>, because the client could reference only the abstract class instead of concrete ones.<\/p>\n<p style=\"color: #555555;\"><strong>Strategy<\/strong><\/p>\n<p style=\"color: #555555;\">There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.<\/p>\n<p style=\"color: #555555;\">Let\u2019s use CQLinq to detect all classes using strategy pattern, For this purpose we can search for abstract classes, having multiple derived classes, and where the client reference abstract class instead of the concrete implementations.<\/p>\n<p style=\"color: #555555;\"><span style=\"color: #3366ff;\">from<\/span>\u00a0t\u00a0<span style=\"color: #3366ff;\">in<\/span>\u00a0Types\u00a0<span style=\"color: #3366ff;\">where<\/span>\u00a0t.IsAbstract &amp;&amp;\u00a0<span class=\"skimlinks-unlinked\">t.DirectDerivedTypes.Count()&gt;1<\/span>\u00a0!t.IsThirdParty<br \/>\n<span style=\"color: #3366ff;\">let<\/span>\u00a0tt=t.DirectDerivedTypes<br \/>\n<span style=\"color: #3366ff;\">from<\/span>\u00a0db\u00a0<span style=\"color: #3366ff;\">in<\/span>\u00a0tt\u00a0<span style=\"color: #3366ff;\">where<\/span>\u00a0<span class=\"skimlinks-unlinked\">db.Methods.Where(a=&gt;a.NbMethodsCallingMe!=0<\/span>\u00a0!a.IsStatic).Count()==0<br \/>\n<span style=\"color: #3366ff;\">select<\/span>\u00a0new {db,t}<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror41.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-807\" title=\"ror4\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror41.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\"><em>Motivation:<\/em><\/p>\n<p style=\"color: #555555;\">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.<\/p>\n<p style=\"color: #555555;\">The CameraManager uses the abstract behavior IBehavior, here are all the methods from CameraManager \u00a0using IBehavior class.<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror17.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-796\" title=\"ror17\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror17.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">As we can observe, there is a method named switchBehavior to change the behavior dynamically.<\/p>\n<p style=\"color: #555555;\">This pattern enforces the\u00a0<strong>low coupling<\/strong>, CameraManger doesnt know the concrete behaviors, and also enforces the\u00a0<strong>high cohesion<\/strong>, because each specific behavior is implemented in a isolated class.<\/p>\n<p style=\"color: #555555;\"><strong>State<\/strong><\/p>\n<p style=\"color: #555555;\">State pattern is similar to the Strategy Design Pattern from an architectural point of view, and for this reason for the previous CQLinq request when we searched for strategy pattern, we found also state classes.<\/p>\n<p style=\"color: #555555;\">But the goal is different, the Strategy pattern represents an algorithm that uses one or more IStrategy\u00a0<span class=\"skimlinks-unlinked\">implementations.\u00a0T<\/span>here\u2019s no correlation between these different behavior, however for State pattern we pass from one state to another to acheive the final objective, so there\u2019s a cohesion between the different states.<\/p>\n<p style=\"color: #555555;\">Here are all state classes inheriting from the abstract class AppState<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror18.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-797\" title=\"ror18\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror18.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">Like Strategy pattern, only the abstract class is reference by other classes, here are all the methods using AppState.<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror19.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-798\" title=\"ror19\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror19.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">As we can observe, AppStateManager contains many methods to manage the state lifecycle.<\/p>\n<p style=\"color: #555555;\"><em>Motivation:<\/em><\/p>\n<p style=\"color: #555555;\">Like Strategy patern, this pattern enforces the\u00a0<strong>low coupling<\/strong>, AppStateManger doesnt know the concrete states and also enforces the\u00a0<strong>high cohesion,<\/strong>\u00a0because each traitement is isolated in it\u2019s corresponding state.<\/p>\n<p style=\"color: #555555;\"><strong>Facade<\/strong><\/p>\n<p style=\"color: #555555;\">A facade is an object that provides a simplified interface to a larger body of code, such as a class library. And to detected facades used the simple way is to search for external code used.<\/p>\n<p style=\"color: #555555;\">Here\u2019s all namespaces used by ROR project:<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror121.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-761\" title=\"ror12\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror121.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">let\u2019s take as example the Caelum and search for classes using it from ROR<\/p>\n<p style=\"color: #555555;\"><span style=\"color: #3366ff;\">from<\/span>\u00a0m\u00a0<span style=\"color: #3366ff;\">in<\/span>\u00a0Methods\u00a0<span style=\"color: #3366ff;\">where<\/span>\u00a0m.IsUsing (\u201c<span style=\"color: #ff6666;\">Caelum<\/span>\u201c)<br \/>\n<span style=\"color: #3366ff;\">select<\/span>\u00a0new { m }<\/p>\n<p style=\"color: #555555;\"><a style=\"color: #2970a6;\" href=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror9.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-756\" title=\"ror9\" src=\"http:\/\/cppdepend.files.wordpress.com\/2012\/10\/ror9.png?w=595\" alt=\"\" \/><\/a><\/p>\n<p style=\"color: #555555;\">Only SkyManager use directly Caelum namespace, so it represent the Caelum facade.<\/p>\n<p style=\"color: #555555;\"><em>Motivation<\/em><\/p>\n<p style=\"color: #555555;\">If we use an external library and its highly coupled with our code, i.e. many classes use directly this library, it will be very difficult to change this external library. However, if a facade is used, only its implementation will be changed if we want to change the external library.<\/p>\n<p style=\"color: #555555;\">This pattern enforces the <strong>low coupling<\/strong> with external libraries.<\/p>\n<p style=\"color: #555555;\"><strong>Conclusion<\/strong><\/p>\n<p style=\"color: #555555;\">After learning the GOF patterns, try to not force\u00a0using them because they became popular. But you need to know the motivations behind using them in your code. Discovering the implementation of patterns from known open source projects could help you to understand better the utility of patterns.<\/p>\n<p style=\"color: #555555;\">\n","protected":false},"excerpt":{"rendered":"<p>The majority of developers have already heard about the design patterns,\u00a0GOF(Gang Of Four)\u00a0patterns are the most popularized, and each developer has his way to learn them , we can enumerate: Reading a book. From web sites. From a collegue. Doing a training. Regardless of the method chose, we can learn by heart the patterns and &hellip; <a href=\"https:\/\/codergears.com\/Blog\/?p=720\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Learn design patterns from real projects: RigsOfRods case study.&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-720","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/posts\/720","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=720"}],"version-history":[{"count":12,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/posts\/720\/revisions"}],"predecessor-version":[{"id":732,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=\/wp\/v2\/posts\/720\/revisions\/732"}],"wp:attachment":[{"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=720"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=720"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codergears.com\/Blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=720"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}