<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andreas Poyias on Medium]]></title>
        <description><![CDATA[Stories by Andreas Poyias on Medium]]></description>
        <link>https://medium.com/@andreaspoyias?source=rss-ad8b7380b7ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P_EpaoF9fcDrX_tb_rOZRg.jpeg</url>
            <title>Stories by Andreas Poyias on Medium</title>
            <link>https://medium.com/@andreaspoyias?source=rss-ad8b7380b7ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 04:39:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreaspoyias/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Λεξούλα — Το απόλυτο Ελληνικό Wordle]]></title>
            <link>https://medium.com/@andreaspoyias/%CE%BB%CE%B5%CE%BE%CE%BF%CF%8D%CE%BB%CE%B1-%CF%84%CE%BF-%CE%B1%CF%80%CF%8C%CE%BB%CF%85%CF%84%CE%BF-%CE%B5%CE%BB%CE%BB%CE%B7%CE%BD%CE%B9%CE%BA%CF%8C-wordle-f7f0bb769455?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f0bb769455</guid>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 21:59:32 GMT</pubDate>
            <atom:updated>2022-02-22T07:23:30.794Z</atom:updated>
            <content:encoded><![CDATA[<h3>Λεξούλα — Το απόλυτο Ελληνικό Wordle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*jsvzMeq46lLJnRm_lHN8jg.png" /></figure><p>Η Λεξούλα <strong>(</strong><a href="https://lexoula.com/"><strong>https://lexoula.com</strong></a><strong>)</strong> ήρθε στη ζωή μας να μας προσφέρει ένα μικρό διάλειμμα στη βαρετή καθημερινότητα της πανδημίας. Είναι γνωστή ως το ελληνικό Wordle (Greek Wordle). Οι κανόνες απλοί: ο χρήστης έχει έξι προσπάθειες για να μαντέψει μια λέξη με πέντε γράμματα, σε κάθε προσπάθεια πολύχρωμα τετραγωνάκια δείχνουν εάν τα γράμματα υπάρχουν στη λέξη και εάν βρίσκονται στη σωστή θέση ή όχι. Ο μινιμαλιστικός σχεδιασμός και η ευκολία στη χρήση είναι αυτό που έκανε τους χρήστες να το αγαπήσουν. Είναι δωρεάν, δεν απαιτείται εγγραφή λογαριασμού, και το παιχνίδι διαρκεί για 2–3 λεπτά και μόνο μία φορά την ημέρα.</p><p>Η Λεξούλα έχει ξεχωρίσει ως το απόλυτο ελληνικό Wordle. Οι εγκέφαλοι πίσω από το<strong> </strong><a href="https://lexoula.com/"><strong>https://lexoula.com</strong></a> Έρμος Κυριακίδης και Ανδρέας Πογιάς έχουν αφιερώσει πολύ χρόνο για να εντοπίσουν και να επιλέξουν όλες τις πιθανές λέξεις 5 γραμμάτων που θα μπορούσαν να χρησιμοποιηθούν. Αυτό είναι σημαντικό καθώς το παιχνίδι δεν επιτρέπει στον παίκτη να εισαγάγει μια μη έγκυρη ελληνική λέξη. Χρησιμοποιώντας τεχνικές όπως <strong>Data Scraping</strong> και <strong>Data Crawling</strong>, βρήκαν όλες τις πιθανές ελληνικές λέξεις 5 γραμμάτων από κείμενα στο διαδίκτυο και σύγχρονη ελληνική λογοτεχνία. Επίσης, χρησιμοποίησαν μεθοδολογίες εξόρυξης δεδομένων, όπως <strong>Frequent Pattern Mining</strong> and <strong>Sequence Prediction Mining</strong> για να ταξινομήσουν τις λέξεις που θεωρούνται κατάλληλες για το παιχνίδι ή αλλιώς οι ¨επιλεγμένες¨ λέξεις. Μόνο οι ¨επιλεγμένες¨ λέξεις είναι αυτές που χρησιμοποιούνται ως λέξη της ημέρας.</p><p>Η ταξινόμηση αυτή έχει να κάνει με δύο παραμέτρους,</p><ol><li>Ποιά λέξη χρησιμοποιείτε πιο συχνά στην λογοτεχνία και στη καθημερινότητα (Frequent Pattern Mining)</li><li>Ποιά κλίση της συγκεκριμένης λέξης είναι πιο συχνή (Sequence Prediction Mining).</li></ol><blockquote>Η ταξινόμηση ¨επιλεγμένων¨ λέξεων είναι πολύ σημαντική για την ικανοποίηση και ψυχαγωγία των χρηστών. Ο χρήστης δεν πρέπει προσπαθεί να μαντέψει μια λέξη που δεν χρησιμοποιεί καθημερινά ή να ξοδεύει τρείς από της έξι προσπάθειες του για να βρει την επιθυμητή κλίση της.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f0bb769455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Decorator pattern.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/2159b97863f</guid>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 19:01:01 GMT</pubDate>
            <atom:updated>2019-09-29T06:17:49.040Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Decorator pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iLpXtAFEXkc5gulNfL6tKA.jpeg" /></figure><p>The <strong>Decorator pattern </strong>is a structural pattern that lets you attach additional functionalities to an object dynamically. In other words, the client has the freedom to create an object and then extend it by adding a variety of “features” to it. A good analogy to simplify this pattern is: “<em>Wrapping a gift, putting it in a box, and wrapping the box</em>”.</p><blockquote>The <strong>Decorator pattern </strong>is classified among s<strong>tructural</strong> design patterns which are all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality. [by <a href="https://sourcemaking.com/design-patterns-ebook">Design Patterns explained simply</a>]</blockquote><p>A <strong>backpack</strong> in the perfect <strong>example </strong>of a Decorator pattern:</p><ul><li>Nowadays, the backpacks can have a variety of features. The features can range from something as simple as a laptop slot, side pockets, or even a power-bank for USB charging.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*1GaSMfJstV-CpSHxbl7ipA.jpeg" /></figure><ul><li>The main target of the <strong>Decorator</strong> <strong>pattern </strong>is to allow the client to add whatever features are required, dynamically, safely and in the easiest possible way. It should be as straight forward and tidy as fitting back the backpack in the picture.</li><li>The snippet of code below is purposely written as it converges so nicely with the quote we mentioned above: “<em>Wrapping a gift, putting it in a box, and wrapping the box</em>”. We assemble a backpack <strong><em>to which we add</em></strong> a USB charger<strong> <em>to which we add</em></strong><em> </em>a laptop slot <strong>to which we add</strong> …</li></ul><pre><strong>int main </strong>// the client <br>{ <br>  IBackpack *bp = <strong>new</strong> LaptopSlot(<strong>new</strong> UsbCharge(<strong>...</strong>))));<br>  <strong>return</strong> 1;<br>}</pre><p><strong>Step 1 — Keywords</strong></p><p>Defining <strong>keywords </strong>is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.</p><ul><li><strong>Flexibility: </strong>We want to give to the client the power and flexibility to dynamically add any feature to a component/object, that could be considered valuable.</li><li><strong>Extend functionality: T</strong>he title may be a little bit misleading, this pattern is not only about “decorating” a certain object, but it is mainly about extending its functionality.</li></ul><p><strong>Step 2 — Diagrams by example</strong></p><p>Let’s start explaining the diagram from bottom to top. The target is to “assemble” a backpack and add several functionalities to it.</p><ul><li><strong>Concrete Decorators:</strong> We have three examples of these classes which are responsible to extend an extra functionality each: <strong>(1) LaptopSlot, (2) USBCharge, (3) WaterBottle</strong>. They hold the implementation of the functionality and they can “<strong><em>assemble</em></strong>” a backpack accordingly. Notice that they have a constructor that receives a decorator as a parameter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSdrPvC9MKA5M-6xELGPQA.png" /></figure><ul><li><strong><em>Decorator:</em></strong> This class derives the above classes and inherits from the component which is IBackpack. The decorator also has an instance of IBackpack. After IBackpackis instantiated, it is being used inside the assemble()method.</li><li><strong><em>Concrete Component:</em></strong> This class is the most important piece of the puzzle as it is the key to linking everything together. It is the component (backpack) which is in the plainest form it could get. For example, a <strong>plain</strong> backpack consists only of the “<em>shoulder straps and main compartment</em>”. The plain backpack performs as a start of a chain. It <strong>is passed to</strong> the decorator constructor and itself i<strong>s passed to</strong> the constructor of a concrete decorator (to add specific functionalities i.e. a laptop slot) which can be <strong>passed to</strong> another constructor of a concrete decorator and another and so on.</li><li><strong>Component:</strong> It is an abstract view of the object we want to decorate. We can have different concrete components inheriting from it. In this example we could be separating the “PlainBackpack” as “OfficeBackpack”, “CampingBackpack”, “HikingBackpack” but we choose to keep it simple.</li></ul><p><strong>Step 23— Code by example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias</strong></a><strong>”</strong> or the snippets below (in the order provided) and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a>and run it to <strong>observe the output</strong>. Then read the comments or description below. Take time reading it thoroughly (that means one minute, not less and not more).</p><p><strong><em>IBackpack: <br></em></strong>The following code snippet is a simple inheritance, IBackpackis inherited by PlainBackpackclass. All derived classes must implement assemble(), since it is a pure virtual function = 0;. A plain backpack only has shoulder straps and the main compartment.</p><pre><strong>#include</strong> &lt;iostream&gt;<br><strong>using </strong>namespace std;<br><strong><br>class </strong>IBackpack <br>{<br><strong>public:<br>  virtual void </strong>assemble() = 0;<br>  <strong>virtual </strong>~IBackpack() {}<br>};<br><br><strong>class </strong>PlainBackpack: <strong>public </strong>IBackpack <br>{<br><strong>public:<br>  virtual void </strong>assemble(){<strong>cout</strong>&lt;&lt;&quot;<em>\n ShoulderStraps and mainCompartment</em>&quot;;}<br>};</pre><p><strong><em>BackpackDecorator:</em></strong> <br>The above snippet is responsible for the construction of a plain backpack. <strong><em>Now, let’s decorate it</em></strong> using the BackpackDecorator. The decorator inherits from theIBackpack which means it must implement theassemble() method. It also contains an IBackpackobject which is used to delegate the implementation of the assemble()method depending on the type of m_decorator.</p><pre><strong>class </strong>BackpackDecorator: public IBackpack<br>{<br><strong>public:<br>  </strong>BackpackDecorator(IBackpack* decorator):m_Decorator(decorator) {}<br>  <br>  <strong>virtual void </strong>assemble() <br>  {<br>    m_Decorator-&gt;assemble();<br>  }<br><strong>private:</strong><br>  IBackpack* m_Decorator;<br>};</pre><p><strong><em>Concrete decorators:<br></em></strong>The snippet below shows three different decorators that are derived from theBackpackDecorator class which itself inherits fromIBackpack. In this example, they are all identical apart from the implementation ofassemble(). The first adds a <strong><em>laptopSlot</em></strong>, the second adds a <strong><em>UBCharge </em></strong>and the third adds a <strong><em>waterBottle</em></strong>.</p><pre><strong>class </strong>WithLaptopSlot : <strong>public </strong>BackpackDecorator<br>{<br><strong>public:</strong><br>  WithLaptopSlot(IBackpack* dcrator):BackpackDecorator(dcrator){}<br>  <strong>virtual void </strong>assemble() <br>  {<br>    BackpackDecorator::assemble();<br>    <strong>cout </strong>&lt;&lt; &quot;<em> + LaptopSlot</em>&quot;;<br>  }<br>};<br> <br><strong>class </strong>WithUSBCharge : <strong>public </strong>BackpackDecorator<br>{<br><strong>public:<br></strong>    WithUSBCharge(IBackpack* dcrator):BackpackDecorator(dcrator){}<br>    <strong>virtual void </strong>assemble() <br>    {<br>        BackpackDecorator::assemble();<br>        <strong>cout </strong>&lt;&lt; &quot;<em> + USBCharge</em>&quot;;<br>    }<br>};<br> <br><strong>class</strong> WithWaterBottle : <strong>public </strong>BackpackDecorator<br>{<br><strong>public:<br></strong>    WithWaterBottle(IBackpack* dcrator):BackpackDecorator(dcrator){}<br>    <strong>virtual void </strong>assemble() <br>    {<br>        BackpackDecorator::assemble();<br>        <strong>cout </strong>&lt;&lt; &quot;<em> + WaterBottle</em>&quot;;<br>    }<br>};</pre><p><strong><em>Main (Client):<br></em></strong>The main method operates as the <strong>client</strong>(the same as the <a href="https://medium.com/@andreaspoyias">previous guides</a>). We are finally able to put all the pieces of the puzzle together. But before doing so, let’s remember what was mentioned in the first paragraph of the blog “<em>Wrapping a gift, putting it in a box, and wrapping the box</em>”. To understand this we must read the construction of the backpack (in the snippet below) in reverse order:</p><ol><li>Create a PlainBackpack.</li><li>Pass it to the BackpackDecorator.</li><li>Which passes it along to be decorated with a <strong><em>laptop slot</em></strong>.</li><li>In turn, it is passed to be decorated with a <strong><em>USB charge</em></strong>.</li><li>Finally, the “box” is “wrapped” with a <strong><em>water bottle</em></strong>.</li></ol><p>It is also important to observe the print order as assemble()is being called. The order is related to how the constructors were initialized. It again starts from the plain backpack and is decorated all the way with to reach waterbottle.</p><pre><strong>int</strong> main()<br>{<br>  IBackpack* pBackpack = <br>   <strong>new </strong>WithWaterBottle(        //5<br>    <strong>new </strong>WithUSBCharge(         //4<br>     <strong>new </strong>WithLaptopSlot(       //3<br>      <strong>new </strong>BackpackDecorator(   //2<br>       <strong>new </strong>PlainBackpack()))));//1<br><br>  pBackpack-&gt;assemble();<br>  <strong>delete </strong>pBackpack;<br><br>  <strong>return </strong>0;<br>}</pre><pre><strong>// Output<br></strong>// ShoulderStraps and mainCompartment + LaptopSlot + USBCharge<br>// + WaterBottle</pre><p>The simplicity offered to the client is one of the biggest<strong> benefits</strong>.</p><ul><li>The client has the power to dynamically assemble a backpack with any features available.</li><li>It is simple, easy and safe.</li><li>The client does not need to mingle with the code.</li><li>Adding an extra “derived” decorator is simple and independent from other derived decorators.</li></ul><p>Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing. If there is a specific design pattern that you would like to learn about then let me know in the comments below so I can provide it for you in the next few weeks.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2159b97863f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Builder pattern.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a834d7cacead</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 28 Jan 2019 19:01:01 GMT</pubDate>
            <atom:updated>2019-02-08T15:24:40.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Builder pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGC9cgC7N3eUKDafMzRnCw.jpeg" /></figure><p>The <strong>Builder</strong> pattern is a creational design pattern that handles the construction of complex objects step by step (or brick by brick). It is probably the easiest pattern to spot if the existing code needs such design. The <strong>Builder pattern</strong> allows the creation of different <strong>representations </strong>of an object using <strong>the same construction code</strong>.</p><blockquote><strong><em>Builder pattern</em></strong><em> is classified in the </em><strong>creational</strong> design patterns<em> which is all about class/object instantiation. More precisely, how to effectively use inheritance (class-creation patterns) or delegation (object-creation patterns). [by </em><a href="https://sourcemaking.com/design-patterns-ebook"><em>Design Patterns explained simply</em></a><em>]</em></blockquote><p><strong>Example: </strong>Let’s start with an example on my favorite topic. Food!! More precisely the example will be about pizza. Pizza is separated into three layers, the dough, the sauce, and the toppings. Now, let’s ask ourselves, how would we “construct” a pizza object selecting among various toppings and a variety of sauces.</p><p>Questions before designing a solution to this problem:</p><ul><li>How would the Pizza class constructor look like?</li><li>Should we have multiple overloading constructors with parameters for all the combinations like sauces, toppings plus sauces, etc? What if we have different types of dough as well?</li><li>What if later on, we decide to add cheese or different types of cheese? Would that be easy to implement? What about dependencies on existing code?</li><li>Should we just have a default constructor that creates a “plain pizza”? Wouldn’t that force the client to call a number of setters accordingly? Is this safe? What if the client forgets and then we send a plain pizza to the customer?</li></ul><p>The solution to all these questions is the builder pattern. We need a “builder” to construct a pizza step by step. At the same time, the client will be safe to “order” a specific pizza and have the builder build it for him.</p><p><strong>Step 1 — Keywords</strong></p><ol><li><strong>Representation</strong>: An object can have different representations. For example, a pizza can have tomato mozzarella toppings and another representation of pizza would be with mushrooms and parma ham.</li><li><strong>Construction code: </strong>Objects can be constructed in different ways, for example using constructors. Constructors can be <strong>overloaded</strong>, they have the same name (name of the class) but a different number/types of arguments. Depending on the number and type of arguments passed, the specific <strong>constructor</strong> is called.</li></ol><p>It is easy to fall into the trap of having a <em>class</em> of numerous constructors where each one is taking a different number of parameters. The developer is forced to instantiate the class with the correct combination of parameters on each situation. This problem has a name, it is a popular anti-pattern called the <strong><em>telescoping constructor </em></strong>and builder pattern<strong><em> </em></strong>is the go-to solution for it<em>. </em>Let’s oversimplify Builder pattern by bluntly saying:</p><blockquote>The Builder pattern’s main intent is to have the minimum number of overloading constructors to support the constuction of several representations of an object.</blockquote><p><strong>Step 2 — Diagram (By example)</strong></p><p>Let’s stick to the pizza example. In summary, we have the pizza class, the cook and the concrete builders that inherit from the abstract builder. We will explain the diagram bottom to top:</p><ul><li><strong><em>Pizza_Product:</em></strong> This class is the actual pizza. It is represented by three attributes: (1) Dough, (2) sauce and (3) toppings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yp_RZDnUIuuxIBOoNGLdBQ.png" /></figure><ul><li><strong><em>ConcreteBuilder: </em></strong>Each<strong><em> </em></strong>concrete builder is responsible for a specific representation. In this example, we have <strong><em>Margherita </em></strong>and <strong><em>Spicy Pizza</em></strong>. Both concrete builders are responsible to “build” their own representation of pizza based on the three attributes listed above.</li><li><strong><em>AbstractBuilder:</em></strong> Contains a pizza member variable and the concrete builders inherit from it.</li><li><strong><em>Cook_Director: </em></strong>In this example, the director is the actual cook. The class is responsible to initiate the construction of a given representation by putting the pieces together such that the builder will follow and adapt according to the director’s needs.</li></ul><p><strong>Step 3 — Code by example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias</strong></a><strong>”</strong> or the snippets below (in the order provided) and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a>and run it to <strong>observe the output</strong>. Then read the comments or description below. Take time reading it thoroughly (that means one minute, not less and not more).</p><p><strong><em>Product:<br></em></strong>This is the pizza class. It is a simple class with three setters and a taste() method that prints all the ingredients.</p><pre><strong>#include</strong> &lt;iostream&gt;<br><strong>#include</strong> &lt;memory&gt;     // unique_ptr<br><strong>using namespace </strong>std;</pre><pre><strong>class </strong>Pizza_Product<br>{<br><strong>public:</strong><br> <strong>void </strong>setDough(<strong>const string&amp;</strong> dough) { m_dough = dough; }<br> <strong>void </strong>setSauce(<strong>const string&amp;</strong> sauce) { m_sauce = sauce; }<br> <strong>void </strong>setTopping(<strong>const string&amp;</strong> topping) { m_topping = topping; }</pre><pre><strong>void </strong>taste() <strong>const</strong><br>{<br>  <strong>cout </strong>&lt;&lt; &quot;<em>Pizza with </em>&quot; &lt;&lt; m_dough &lt;&lt; &quot; <em>dough</em>, &quot; <br>       &lt;&lt; m_sauce &lt;&lt; &quot; <em>sauce and</em> &quot;<br>       &lt;&lt; m_topping &lt;&lt; &quot; <em>topping</em>. <em>Mmmmmmm</em>.&quot; &lt;&lt; <strong>endl</strong>;<br>}<br><strong>private:<br></strong> <strong>string </strong>m_dough;<br> <strong>string </strong>m_sauce;<br> <strong>string </strong>m_topping;<br>};</pre><p><strong><em>Abstract Builder:<br></em></strong>The abstract builder is an interface that contains a pizza object. It has a getter that returns the pizza object and a method to instantiate the pizza object. It also declares the three builder methods that will be implemented by the concrete builders further down.</p><pre><strong>class </strong>Pizza_Builder<br>{<br><strong>public:<br></strong>  <strong>virtual </strong>~Pizza_Builder() {};</pre><pre>  Pizza_Product* getPizza(){ <strong>return </strong>m_pizza.release(); }</pre><pre><strong>  void </strong>createNewPizzaProduct()<br>  {<br>    m_pizza = make_unique&lt;Pizza_Product&gt;();<br>  }</pre><pre><strong>  virtual void </strong>buildDough() = 0;<br>  <strong>virtual void </strong>buildSauce() = 0;<br>  <strong>virtual void </strong>buildTop()   = 0;</pre><pre><strong>protected:<br></strong>  <strong>unique_ptr&lt;Pizza_Product&gt;</strong> m_pizza;<br>};</pre><p><strong><em>Concrete Builders:<br></em></strong>Two examples of concrete builders and two representations of a pizza. They both implement their own build methods using the m_pizza object from the parent class (Abstract builder)</p><pre><strong>class</strong> Margherita_ConcreteBuilder : public Pizza_Builder<br>{<br><strong>public:<br></strong> <strong>virtual void </strong>buildDough() { m_pizza-&gt;setDough(&quot;<em>cross</em>&quot;); }<br> <strong>virtual</strong> <strong>void </strong>buildSauce() { m_pizza-&gt;setSauce(&quot;<em>tomato</em>&quot;); }<br> <strong>virtual void </strong>buildTop() { m_pizza-&gt;setTopping(&quot;<em>mozzarela+basil</em>&quot;); }<br>};</pre><pre><strong>class </strong>Spicy_ConcreteBuilder : public Pizza_Builder<br>{<br><strong>public:<br></strong> <strong>virtual void </strong>buildDough() { m_pizza-&gt;setDough(&quot;<em>pan baked</em>&quot;); }<br> <strong>virtual void </strong>buildSauce() { m_pizza-&gt;setSauce(&quot;<em>tomato+chilli</em>&quot;); }<br> <strong>virtual void </strong>buildTop(){ m_pizza-&gt;setTopping(&quot;<em>pepperoni+salami</em>&quot;); }<br>};</pre><p><strong><em>Director:<br></em></strong>This class puts everything together. It has a Pizza_Builder variable. It uses the makePizza()to receive a concrete builder as a parameter. Then calls the build operations which work for both representations accordingly. Therefore we achieve the purpose of having one construction-code to represent different types of pizzas. The tastePizza()method is to print the contents of a pizza.</p><pre><strong>class </strong>Cook_Director<br>{<br><strong>public</strong>:<strong><br></strong> <strong>void </strong>tastePizza(){ m_pizzaBuilder-&gt;getPizza()-&gt;taste(); }</pre><pre><strong>void </strong>makePizza(<strong>Pizza_Builder</strong>* pb)<br> {<br>   m_pizzaBuilder = pb;<br>   m_pizzaBuilder-&gt;createNewPizzaProduct();<br>   m_pizzaBuilder-&gt;buildDough();<br>   m_pizzaBuilder-&gt;buildSauce();<br>   m_pizzaBuilder-&gt;buildTop();<br> }</pre><pre><strong>private</strong>:<br> Pizza_Builder* m_pizzaBuilder;<br>};</pre><p><strong><em>Main (client):<br></em></strong> The main method operates as the <strong>client</strong>(the same as the previous guides)<strong>.</strong> It is so easy for the client to be able to build different representations of a pizza. We need the director, and then, by just passing two different concrete builders as a parameter to themakePizza, we will be able totaste two different types of pizzas.</p><pre><strong>int </strong>main()<br>{<br>  <strong>Cook_Director               </strong>cook;<br>  <strong>Margherita_ConcreteBuilder  </strong>margheritaBuilder;<br>  <strong>Spicy_ConcreteBuilder       </strong>spicyPizzaBuilder;</pre><pre>  cook.makePizza(&amp;margheritaBuilder);<br>  cook.tastePizza();</pre><pre>  cook.makePizza(&amp;spicyPizzaBuilder);<br>  cook.tastePizza();<br>}</pre><pre><strong>// Output</strong></pre><pre>//<strong> </strong>Pizza with cross dough, tomato sauce and mozzarela+basil topping. // Mmmmmmm.</pre><pre>// Pizza with pan baked dough, tomato+chilli sauce and<br>// pepperoni+salami topping. Mmmmmmm.</pre><p>Let’s summarise the <strong>benefits </strong>of this pattern:</p><ul><li>There are many possible representations but only one common input.</li><li>We have a standard protocol for creating all possible representations. The steps of this protocol are clearly exposed by a Builder interface.</li><li>There is one derived concrete class for each target representation.</li><li>It is easy for a developer to add a new self-maintained and independent representation (of a Pizza) without the fear of breaking something else.</li><li>The client can simply register the ConcreteBuilder to the Director and get the expected representation.</li></ul><p>The next blog will be a quick guide to the <strong>Decorator </strong>design pattern. It is a structural pattern which is a must have to your knowledge repository. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing. If there is a specific design pattern that you would like to learn about then let me know in the comments below so I can provide it for you in the next few weeks.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a834d7cacead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Bridge pattern.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebf6a77baed</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bridge-pattern]]></category>
            <category><![CDATA[bridge]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Tue, 15 Jan 2019 14:31:00 GMT</pubDate>
            <atom:updated>2019-02-08T15:25:31.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Bridge pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17NS692NQIZA4RAd9S1pug.jpeg" /></figure><p>The<strong> Bridge</strong> pattern is a very important design pattern. It is commonly used in industry as it is an easy way to simplify classes by separating the low-level logic implementation from the high-level definition of a class (which is usually abstracted/inherited). The purpose of this guide is to explain this pattern in three easy, clean steps.</p><blockquote><em>The </em><strong><em>Bridge</em></strong><em> pattern is classified among s</em><strong><em>tructural</em></strong><em> design patterns which are all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality. [by </em><a href="https://sourcemaking.com/design-patterns-ebook"><em>Design Patterns explained simply</em></a><em>]</em></blockquote><p><strong>Step 1 — Keywords</strong></p><p>The formal definition of the <a href="https://www.amazon.co.uk/dp/0201633612/ref=asc_df_020163361257825026/?tag=googshopuk-21&amp;creative=22110&amp;creativeASIN=0201633612&amp;linkCode=df0&amp;hvadid=310831942794&amp;hvpos=1o1&amp;hvnetw=g&amp;hvrand=7695720308617880081&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9041110&amp;hvtargid=pla-395340045790&amp;th=1&amp;psc=1">Gang of Four (GoF) book</a> — the first people to introduce the design patterns: <em>“Bridge pattern decouples an </em><strong><em>abstraction </em></strong><em>from its </em><strong><em>implementation </em></strong><em>so that the two can vary independently.”</em></p><ul><li><strong>Abstraction </strong>is a high-level interface that contains non-specific implementation of any control logic (or business logic).</li><li>The logic is separated from abstraction and it exists in a different object the “<strong>implementation </strong>object” which is responsible for the low-level work.</li></ul><p>The abstraction contains a reference to the implementation object, therefore it can control its methods. Let’s dive into an example with the use of diagrams.</p><p><strong>Step 2 —Diagrams<br>Design Bridge pattern by example</strong></p><p>In this example, we have three animals that “move” in different ways:</p><ul><li><strong>Person </strong>that moves by <strong>walking</strong>. (We are all animals at the end of the day)</li><li><strong>Fish </strong>that moves by <strong>swimming</strong>.</li><li><strong>Bird </strong>that moves by <strong>flying</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*qTvyoEzU4jvOh79I8GDBww.png" /></figure><p><strong>Abstraction:</strong> It is only obvious that there is a pattern here. Three objects that move but in different ways. Why don’t we make an abstraction out of it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*lbEfQ5eFhEBvCMz_uNvN_g.png" /></figure><p>As shown in the diagram, the class Animal is an abstraction (or interface) such that the three animals inherit from it. Each animal individually implements their own specific logic as to how they move(). Therefore, they declare their own move method.<br>However, we are still not quite there yet. Bridge pattern is <strong>NOT</strong> about a simple inheritance. The pattern’s intent is to <strong>separate </strong>the move()logic from the abstraction. In this example, the code within the Animal classes should only be about defining the animal object representations.</p><p><strong>Implementation:</strong> Each move()method has a different logic (or control logic, or business logic). For example, a person walks by using his legs one at a time, a bird needs to flap its wings in a specific frequency and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*dK84kHPpzCiQFRAKCXK5Sw.png" /></figure><p>The diagram shows the full scale of the bridge pattern. The animals don’t implement their own move()methods but they have a MoveLogic object that they refer to. The move() implementation is decoupled from the Animal interface. The benefit is that the code in the Animal class is cleaner, easy to understand and smaller. Developers don’t need classes with thousand lines of code which is irrelevant to the object&#39;s definition. In addition, if in the future we would like to add a new class, for example, Reptilewe can use the existing Swim class instead of copy pasting the logic inside the Reptile class.</p><p><strong>Step 3 — Code by example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias</strong></a><strong>”</strong> or the snippets below (in the order provided) and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a>and run it to <strong>observe the output</strong>. Then read the comments or description below. Take your time, reading it thoroughly (that means one minute, not less and not more).</p><p><strong><em>Implementation:</em><br></strong>First, we start with the implementation objects. We have the different types of movement likeWalk and Swim, inheriting fromMoveLogic. Each of those classes contains the logic required for the specificmove() function “hiding” the implementation from the Animals. This probably sounds familiar to another design pattern from a previous blog (<a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6"><strong>the Facade pattern</strong></a>). The main difference between the two is the intent. One could easily say that the MoveLogic could as well be the Facade such that the Animal classes don’t contain and maintain the complexities of the move operation.</p><pre><strong>#include</strong>&lt;iostream&gt;<br><strong>#include</strong>&lt;string&gt;<br><strong>using </strong>namespace std;<br> <br><strong>class </strong>MoveLogic {<br><strong>public:<br></strong>    <strong>virtual void </strong>move() = 0;<br>};<br> <br><strong>class </strong>Walk : <strong>public </strong>MoveLogic {<br><strong>public:<br></strong>    <strong>void </strong>move() { <strong>cout </strong>&lt;&lt; &quot;Move alternating legs<strong>\n</strong>&quot;; }<br>};<br> <br><strong>class </strong>Fly : <strong>public </strong>MoveLogic {<br><strong>public:<br></strong>    void move() { <strong>cout </strong>&lt;&lt; &quot;Flap wings<strong>\n</strong>&quot;; }<br>};</pre><p><strong><em>Abstraction:</em><br></strong>This is a simple inheritance from an interface. Each animal’s is constructor receives a MoveLogic object to be initialized. Then the animal can call the move() function where the move is going to perform the complicated logic that is required.</p><pre><strong>class </strong>Animal {<br><strong>public:<br></strong>    <strong>virtual void </strong>howDoIMove() = 0;<br>};<br> <br><strong>class </strong>Person : <strong>public </strong>Animal {<br>    MoveLogic* _myMoveLogic;<br><strong>public:<br></strong><em>    // Constructor receives the MoveLogic object to be initialized<br></em><strong>    </strong>Person(MoveLogic *obj): _myMoveLogic(obj){}</pre><pre>    <strong>void </strong>howDoIMove() {<br>        _myMoveLogic-&gt;move();<br>    }<br>};<br> <br><strong>class </strong>Bird : <strong>public </strong>Animal {<br>    MoveLogic* _myMoveLogic;<br><strong>public:<br></strong>    Bird(MoveLogic *obj) :_myMoveLogic(obj){}<br>    <strong>void </strong>howDoIMove() {<br>        _myMoveLogic-&gt;move();<br>    }<br>};</pre><p><strong><em>Main function</em></strong><em><br></em>As always (in my examples) the main function operates as the <strong>client.</strong> The client’s job is simple. MoveLogic objects are created, then they are passed to the animals which use the decoupled move implementation.</p><pre><strong>int </strong>main() <br>{<br>    MoveLogic* walk = <strong>new </strong>Walk();<br>    MoveLogic* fly  = <strong>new </strong>Fly();<br> <br>    Animal* animalA = <strong>new </strong>Person(walk);<br>    Animal* animalB = <strong>new </strong>Bird(fly);<br> <br>    animalA-&gt;howDoIMove();<br>    animalB-&gt;howDoIMove();<br> <br>    <strong>return </strong>1;<br>}</pre><pre>// <strong>Output:</strong><br>// Move alternating legs<br>// Flap wings</pre><p>The next blog will be a quick guide to the <strong>Builder </strong>design pattern. It is a creational pattern which is a must have to your knowledge repository. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing. If there is a specific design pattern that you would like to learn about then let me know so I can provide it for you in the future.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2IVAl0TbsfES9cFGYr40g.png" /></a></figure><p><strong>This story is published in Noteworthy, where 10,000+ readers come every day to learn about the people &amp; ideas shaping the products we love.</strong></p><p><strong>Follow our publication to see more product &amp; design stories featured by the </strong><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_text"><strong>Journal</strong></a><strong> team.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebf6a77baed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Observer pattern.]]></title>
            <link>https://medium.datadriveninvestor.com/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0622145d6c2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 18:31:01 GMT</pubDate>
            <atom:updated>2019-02-08T15:27:01.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Observer pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-BQRm6Q-85lJW1kWodAwQ.png" /></figure><p><strong>Observer </strong>pattern is a very commonly used pattern. In fact, it is so common that is being standardized in many programming languages/libraries. In Java, it exists injava.util.Observer (deprecated in Java 9). In Python it as close as apip install pattern-observer. In C++, we can sometimes use boost library, more precisely #include &lt;boost/signals2.hpp&gt;. However, it is widely used in industry as a custom-made solution. To be able to use it correctly and understand its complexity, we need to dive in and explore it.</p><blockquote><strong>Observer </strong>pattern is classified among the behavioral design patterns. Behavioral design patterns are most specifically concerned with communication between classes/objects. [by <a href="https://sourcemaking.com/design-patterns-ebook">Design Patterns explained simply</a>]</blockquote><p>What is an <strong>observer pattern</strong>? Apart from a walking monitor that broadcasts analog television (as in the picture). The pattern’s aim is to define a one-to-many relationship such that when one object changes <strong>state</strong>, the others are <strong>notified </strong>and <strong>updated </strong>automatically. More precisely, it wishes to be informed about events happening in the system. Lets put the pieces of the puzzle together in three steps.</p><p><strong>Step 1 — Keywords</strong></p><p>Defining <strong>keywords </strong>is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.</p><ol><li><strong>Subject: </strong>It is considered as the keeper of information, of data or of business logic.</li><li><strong>Register/Attach</strong>: Observers register themselves to the subject because they want to be notified when there is a change.</li><li><strong>Event:</strong> Events act as a trigger in the subject such that all the observers are notified.</li><li><strong>Notify:</strong> Depending on the implementation, the subject may “push” information to the observers, or, the observers may “pull” if they need information from the subject.</li><li><strong>Update: </strong>Observers update their state independently from other observers however their state might change depending on the triggered event.</li></ol><p><strong>Step 2 — Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FR3gyD7PlBwxFiflUhklQ.png" /></figure><p>Lets split this design into different classes to simplify this a little bit.</p><ul><li>The <strong>ConcreteObservers </strong>are classes that contain information specific to the current instance. The update function is called by the subject’s notify() operation. The observers update independently based on their current state.</li><li>The <strong>Observer </strong>is the parent class of the concrete observers. It contains a subject instance. When an observer is initialized, it registers/attaches itself to the subject.</li><li>The <strong>Subject </strong>class has a list or a collection of observers. When an event is triggered it calls the notify()operation which loops through all the observers by calling their update function.</li></ul><p><strong>Step 3 — Code by Example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias</strong></a><strong>”</strong> or the snippets below (in the order provided) and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a> and run it to <strong>observe the output</strong>. Then read the comments or description below. Take your time, reading it thoroughly (that means one minute, not less and not more).</p><p><strong>Example: </strong>Consider a football game. Many supporters are watching the game. We split the supporters into two categories by age, young and old. When their team scores a goal the supporters react differently according to their age and their excitement level. <br>Now, let’s talk with terms used for the observer pattern:</p><ul><li>The game is the <strong>subject </strong>and the supporters are the <strong>observers</strong>.</li><li>All observers are <strong>attached/registered</strong> to the subject and they are <strong>notified </strong>when their football team scores (the <strong>trigger-event</strong> is if their team scores).</li><li>The observers <strong>update </strong>their behavior depending on the notification received.</li></ul><p><strong><em>Subject<br></em></strong>For this class, we need access to a list of observers. When the observers are about to register, they call theattach(this) function to add themselves to the available list (this is an observer&#39;s instance). When an event is triggered wenotify() all of the observers to independently update their state. In this example, the trigger is if the observer’s football team scored.</p><pre><strong>#include</strong> &lt;iostream&gt;<br><strong>#include</strong> &lt;vector&gt;<br><strong>using </strong>namespace std;</pre><pre><strong>class </strong>Subject {<br>    <strong>vector </strong>&lt; class Observer * &gt; observers; <br>    <strong>bool </strong>scored;                    <em>// trigger, event</em></pre><pre><strong>public:<br>    </strong><em>// register observers</em><strong><br></strong>    <strong>void </strong>attach(Observer *obs) {<br>        observers.push_back(obs);<br>    }<br>   <br><em>   // This is the EVENT<br>   // set the if scored and notify ALL observers</em><br>   <strong>void </strong>setScored(bool Score) {<br>      scored = Score;<br>      notify();<br>   }</pre><pre><strong>bool </strong>getScored() {<br>      <strong>return </strong>scored;<br>   }</pre><pre>  <em> // notify implementaion is further down<br>   // so that the script compiles and runs</em><br>   <strong>void </strong>notify();<br>};</pre><p><strong><em>Observer<br></em></strong>This class is dependent on the subject it is registered with. When concrete observers get initialized they attach themselves to theSubject. In this example, the <strong>state </strong>of each observer is his excitementLevelabout the game.</p><pre><strong>class </strong>Observer <br>{<br>    <strong>Subject </strong>*subj;<br>    <strong>int </strong>excitementLevel;               <em>// state</em></pre><pre>  <strong>public</strong>:<br>    Observer(Subject *mod, int excLevel) <br>    {<br>        subj = mod;<br>        excitementLevel = excLevel;<br>        <em>// Observers register/attach themselves with the Subject</em><br>        subj-&gt;attach(this);<br>    }</pre><pre>    <strong>virtual void </strong>update() = 0;</pre><pre>  <strong>protected</strong>:<br>    <strong>Subject </strong>*getSubject() {<br>       <strong>return </strong>subj;<br>    }</pre><pre>    <strong>void </strong>setExcitementLevel(int excLevel) {<br>       excitementLevel = excLevel;<br>    }</pre><pre>    <strong>int </strong>getExcitementLevel() {<br>       <strong>return </strong>excitementLevel;<br>    }<br>};</pre><p>This is theSubject::notify() declaration and as we mentioned before its job is to notify all observers to update their state.</p><pre><strong>void </strong>Subject::notify() {<br>  for (int i = 0; i &lt; observers.size(); i++)<br>    observers[i]-&gt;<strong>update</strong>();<br>}</pre><p><strong><em>Concrete Observers<br></em></strong>The concrete observers inherit from the Observer class and they all must have the update function. In this example, the concrete observers are distinguished between young and old supporters. If their excitement level gets too high the older supporters have the risk of heart attacks and the younger ones have the risk of drink and drive. Their state updates independently as we will prove in the main function further below.</p><pre><strong>class </strong>Old_ConcreteObserver: <strong>public </strong>Observer <br>{<br>   <strong>public</strong>:<br><em>     // Calls parent constructor to register with subject<br></em>     <strong>Old_ConcreteObserver</strong>(Subject *mod, int div)<br>        :Observer(mod, div){}</pre><pre>     // For older people, if the excitement level <br><em>     // is over 150 they run risk of heart attack<br></em>     <strong>void </strong>update() <br>     {<br>        <strong>bool </strong>scored = getSubject()-&gt;getScored(); <br>        setExcitementLevel(getExcitementLevel() + 1);</pre><pre><strong>        if </strong>(scored &amp;&amp; getExcitementLevel() &gt; 150) <br>        {<br>          <strong>cout </strong>&lt;&lt; &quot;Old Observer&#39;s team scored!!&quot; <br>               &lt;&lt; &quot; His excitement level is &quot; <br>               &lt;&lt; getExcitementLevel() <br>               &lt;&lt; &quot; watch out of heart attacks!&quot; &lt;&lt; <strong>endl</strong>;<br>        }<strong>else</strong>{<br>          <strong>cout </strong>&lt;&lt; &quot;Team didn&#39;t score. Yeeeih nothing to worry about&quot;<br>               &lt;&lt; <strong>endl</strong>;<br>        }<br>    } // end update()<br>};</pre><pre><strong>class </strong>Young_ConcreteObserver: <strong>public </strong>Observer <br>{<br>   <strong>public</strong>:<br><em>     // Calls parent constructor to register with subject<br>  </em>   <strong>Young_ConcreteObserver</strong>(Subject *mod, int div)<br>       : Observer(mod, div){}</pre><pre>     // For older people, if the excitement level <br><em>     // is over 100 they run risk of heart attack<br>     </em><strong>void </strong>update() <br>     {<br>        <strong>bool </strong>scored = getSubject()-&gt;getScored(); <br>        setExcitementLevel(getExcitementLevel() + 1);</pre><pre><strong>        if </strong>(scored &amp;&amp; getExcitementLevel() &gt; 100) <br>        {<br>          <strong>cout </strong>&lt;&lt; &quot;Young Observer&#39;s team scored!!&quot; <br>               &lt;&lt; &quot; His excitement level is &quot; <br>               &lt;&lt; getExcitementLevel() <br>               &lt;&lt; &quot; dont&#39;t drink and drive!!&quot; &lt;&lt; <strong>endl</strong>;<br>        }<strong>else</strong>{<br>          <strong>cout </strong>&lt;&lt; &quot;Team didn&#39;t score. Yeeh nothing to worry about&quot;<br>               &lt;&lt; <strong>endl</strong>;<br>       }<br>    } // end update()<br>};</pre><p><strong><em>Main function</em></strong><em><br></em>The concrete observers register themselves to theSubject instance. Their state is the excitement level which is the second parameter. When the event is triggered “subj.setScored(true)”, thenSubject::notify() is called to update the registered observers. In the scenario below, we have three observers, the youngObs1is overexcited and runs the risk of drink and drive, the oldObs1is also overexcited a runs a different risk (of heart attack). Finally, youngObs2 who is also young as the first one has nothing to worry about as he is not overexcited.</p><blockquote>It is important to notice that the three observers updated independently based on their state (excitement level) and their type (young or old).</blockquote><pre><strong>int </strong>main() {<br>   <strong>Subject </strong>subj;<br>   <strong>Young_ConcreteObserver </strong>youngObs1(&amp;subj, 100); <br>   <strong>Old_ConcreteObserver </strong>oldObs1(&amp;subj, 150); <br>   <strong>Young_ConcreteObserver </strong>youngObs2(&amp;subj, 52);<br>   subj.setScored(true);<br>}</pre><pre>// Output<br>// Young Observer&#39;s team scored!! His excitement level is 101<br>// dont&#39;t drink and drive!! </pre><pre>// Old Observer&#39;s team scored!! His excitement level is 151 watch <br>// out of heart attacks! Team didn&#39;t score. </pre><pre>// Yeeh nothing to worry about</pre><p>There are a few <strong>benefits </strong>for the use of Observer pattern and a few points to be noted when this pattern is to be approached<a href="https://www.amazon.co.uk/Learning-Python-Design-Patterns-Second/dp/178588803X/ref=sr_1_2?s=books&amp;ie=UTF8&amp;qid=1545412098&amp;sr=1-2&amp;keywords=learning+python+design+patterns">[Learning Python Design Patterns]</a>.</p><ul><li>The Observer pattern provides a design where the Subject and Observer are <strong>loosely coupled</strong>. The subject does not need to know about the ConcreteObserver class. Any new Observer can be added at any point in time. There is no need to modify the Subject when a new Observer is added. Observers and subjects are not tied up and are independent of each other, therefore, changes in the Subject or Observer will not affect each other.</li><li>There is no option for composition, as the Observer interface can be instantiated.</li><li>If the Observer is misused, it can easily add complexity and lead to performance issues.</li><li>Notifications can be unreliable and may result in race conditions or inconsistency.</li></ul><p>The next blog will be a quick guide to the <strong>Bridge </strong>design pattern. It is a structural design pattern which is used quite a lot in the industry. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing. If there is a specific design pattern that you would like to learn about then let me know so I can provide it for you in the future.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0622145d6c2" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to Observer pattern.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Facade pattern.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/16e3d2f1bfb6</guid>
            <category><![CDATA[facade-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 19:01:00 GMT</pubDate>
            <atom:updated>2019-02-08T15:26:32.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Facade pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3QxZm04yq3u5zotdaiKKA.jpeg" /></figure><p>Facade pattern is often needed when there is a large number of interdependent classes or because parts of the code are unavailable. It is used as a camouflage to cover the complexities of a large system and therefore provides a simple interface to the client. In other words, it is a wrapper class used to hide the implementation details.</p><blockquote><strong>Facade pattern</strong> is classified as a structural design pattern. This design patterns is all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality. [by <a href="https://sourcemaking.com/design-patterns-ebook">Design Patterns explained simply</a>]</blockquote><p>The picture above is the perfect <strong>example </strong>of a Facade pattern. A customer in a restaurant orders food from the menu, which is probably described in half a line. The order goes to the kitchen and the food comes back after a while. <strong>Simple!</strong> The customer doesn’t want to know who will cut the meat for how long will it be cooked and who is going to wash the dishes afterward. The customer just wants to eat a tasty meal that meets the expectations. Therefore, the menu serves as the facade to make it easier for the customer by avoiding the complexities coming from the kitchen or even the tasks that the waiter is assigned through this process.</p><p><strong>Step 1 — Keywords</strong></p><p>Defining <strong>keywords </strong>is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.</p><ol><li><strong>Simplification</strong>: This is the goal of this design pattern. Simplify a complicated system.</li><li><strong>Restriction</strong>: Simplification often comes with a “sacred cost”, restriction. By simplifying the code, we restrict clients from unauthorized access. Therefore, it prevents them from doing mistakes that would be difficult to be perceived in a complicated subsystem.</li></ol><p>There is a tradeoff between simplification and restriction. Over-simplifying a system means that the developer is over-restricted, therefore less freedom than necessary which not always a good thing. Under-simplifying Facade pattern means that there is too much freedom which makes the Facade pattern irrelevant. Finding the fine balance is what makes a good, useful and effective Facade pattern.</p><p><strong>Step 2 — Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nrm8teBV3PNZIiR9gtuSqg.png" /></figure><p>The diagram is also based on the given example. To simplify this diagram we can separate into three pieces.</p><ol><li><strong>Client:</strong> The client in this example is the customer of a restaurant that wants to order food.</li><li><strong>Facade:</strong> Its job is to be able to provide to the client more simplified access towards numerous interdependent subsystems that are considered complicated. In this example, a client’s food-order would require a series of carefully sequenced method calls of two different subsystems (Waiter and Kitchen).</li><li><strong>Subsystems:</strong> The subsystems are hidden from the client. They might also be not accessible to the client. The client cannot fiddle with any of the subsystems where a simple code-change may prove to be fatal or even break other unknown parts of the system itself. In this scenario, the waiter and the kitchen have to do a series of tasks. A subsystem’ s task is sometimes dependent on the anothers task. For example, the kitchen cannot prepare the food if the waiter doesn’t bring the order to the kitchen. The waiter cannot serve the customer if the food is not cooked.</li></ol><p><strong>Step 3 — Code by example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias</strong></a><strong>”</strong> or the snippets below (in the order provided) and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a> and run it to <strong>observe the output</strong>. Then read the comments or description below. Take your time, reading it thoroughly (that means one minute, not less and not more).</p><p><strong><em>Subsystems</em></strong></p><p>In this example, the two subsystems are the Waiter_Subsystem1and theKitchen_Subsystem2. At a first glance, each subsystem seems to be independent as they can do certain tasks individually. But is this true?</p><pre><strong>#include </strong>&lt;iostream&gt;<br><strong>using </strong>namespace std;</pre><pre><strong>class </strong>Waiter_Subsystem1<br>{<br><strong>public:<br></strong>  <strong>void </strong>writeOrder()   { <strong>cout </strong>&lt;&lt; &quot; Waiter writes client&#39;s order\n&quot;;}<br>  <strong>void </strong>sendToKitchen(){ <strong>cout </strong>&lt;&lt; &quot; Send order to kitchen\n&quot;;}<br>  <strong>void </strong>serveCustomer(){ <strong>cout </strong>&lt;&lt; &quot; Yeeei customer is served!!!\n&quot;;}<br>};</pre><pre><strong>class </strong>Kitchen_Subsystem2<br>{<br>public:<br>    <strong>void </strong>prepareFood(){ <strong>cout </strong>&lt;&lt; &quot; Cook food\n&quot;;}<br>    <strong>void </strong>callWaiter() { <strong>cout </strong>&lt;&lt; &quot; Call Waiter\n&quot;;}<br>    <strong>void </strong>washDishes() { <strong>cout </strong>&lt;&lt; &quot; Wash the dishes\n&quot;;}<br>};</pre><p><strong><em>Facade: </em></strong>In this example, the Facade class is about food-orders in the restaurant. To execute a food-order successfully, we rely on a specific sequence of method calls and one call is dependent on the previous one and so on. The kitchen, cannot prepare the food if the waiter doesn’t write the order and send it to the kitchen. The Facade class provides theorderFood task to the client to simplify it and avoid any misuse due to the complexity that exists.</p><pre><strong>class </strong>Order_Facade<br>{<br><strong>private:<br></strong>    Waiter_Subsystem1waiter;<br>    Kitchen_Subsystem2 kitchen;<br><strong>public:<br></strong>    <strong>void </strong>orderFood()<br>    {<br>        <strong>cout </strong>&lt;&lt; &quot;A series of interdependent calls on various subsystems:\n&quot;;<br>        waiter.writeOrder();<br>        waiter.sendToKitchen();<br>        kitchen.prepareFood();<br>        kitchen.callWaiter();<br>        waiter.serveCustomer();<br>        kitchen.washDishes();<br>    }<br>};</pre><p><strong><em>Main function</em></strong><em><br></em>The main function operates as the <strong>client</strong>(the same as the previous guides)<strong>.</strong> It is so easy for the client to be able to create a Facade instance and call a function to do his job.</p><pre><strong>int</strong> main(<strong>int</strong> argc, <strong>char</strong> *argv[])<br>{<br>    // Simple for the client <br>    // no need to know the order or the <br>    // dependencies among various subsystems.<br>    <strong>Order_Facade</strong> facade;<br>    facade.orderFood();</pre><pre><strong>return</strong> 0;<br>}</pre><pre><strong>//</strong> <strong>Output</strong><br>// A series of interdependent calls on various subsystems:<br>//  Waiter writes client&#39;s order<br>//  Send order to kitchen<br>//  Cook food<br>//  Call Waiter<br>//  Yeeei customer is served!!!<br>//  Wash the dishes</pre><p>There are a few <strong>benefits </strong>for the use of Facade pattern and a few points to be noted when Facade is to be approached.</p><ul><li>Facade defines a higher-level interface that makes the subsystem easier to use by wrapping a complicated subsystem.</li><li>This reduces the learning curve necessary to successfully leverage the subsystem.</li><li>It also promotes <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)">decoupling</a> the subsystem from its potentially many clients.</li><li>On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that “power users” may need.</li></ul><p>The next blog will be a quick guide to the <a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2"><strong>Observer</strong></a><strong> </strong>design pattern. It is a behavioral pattern which is a must have to your knowledge repository. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing. If there is a specific design pattern that you would like to learn about then let me know so I can provide it for you in the future.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16e3d2f1bfb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Singleton pattern.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/60732ed43956</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 19:01:01 GMT</pubDate>
            <atom:updated>2019-02-08T15:27:16.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Singleton pattern.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5i8uZEhcWBFFEK0Kfqp_0g.png" /></figure><p>This is another quick-guide to mastering a very commonly used design pattern, the <strong>Singleton pattern</strong>. Singleton pattern is one of the simplest but most controversial design patterns (with pros and many cons). This is one of the main reasons why it is very <strong>common in programming interviews</strong>.</p><blockquote><strong>Singleton pattern</strong> is classified in the <strong><em>creational</em></strong><em> design patterns</em> which is all about class/object instantiation. More precisely, how to effectively use inheritance (class-creation patterns) or delegation (object-creation patterns). [by <a href="https://sourcemaking.com/design-patterns-ebook">Design Patterns explained simply</a>]</blockquote><p><strong>Singleton definition:</strong> In mathematics, is defined as “<em>a set which contains exactly one element</em>”. This pattern is very simple to understand and easy to implement since it is only a few lines of code and the application is quite straight-forward. <strong>It is a pattern that ensures a class has only one instance and provides a global point of access to it.</strong> For example, we can only have one active Pope of Italy, therefore, it is possible that the Pope can be represented with a Singleton pattern.</p><p><strong>Step 1 — Keywords</strong></p><p>Defining <strong>keywords </strong>is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.</p><p>This time the keywords take us a trip <strong>back to basics</strong>. It is an introduction to the very simple code that will follow. Feel free to skip to the next step if you feel comfortable with the terms.</p><ol><li><strong>Class-instance</strong>: An instance is a concrete occurrence of any object. It exists usually during the runtime of a computer program and it emphasizes in distinctly identifying the object. Similarly, class-instances are created from classes by subroutines like constructors/destructors.</li><li><strong>Private Constructor:</strong> A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create <strong>instances</strong> of this class.</li><li><strong>Static data members: </strong>When we declare a member of a class as static it means no matter how many objects of the class are created, <strong>there is only one copy</strong> of the static member. [<a href="https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm">from TutorialPoint</a>]</li><li><strong>Static Function:</strong> A static member function can be <strong>called even if no objects of the class exist.</strong> [<a href="https://www.tutorialspoint.com/cplusplus/cpp_static_members.htm">from TutorialPoint</a>]</li></ol><p><strong>Step 2 — Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zijysDjydnIfKsrOh5ghzQ.png" /></figure><p>There are one-two programming tricks to make a class Singleton. Other than that it is quite trivial. Reading the diagram from top to bottom: We should have</p><ul><li>A static(underlined) and private(-) instance of the class</li><li>A private constructor.</li><li>A public(+) and static function that returns the instance.</li></ul><p>Class definition should not be more than 7–8 lines of code, depending on the programming language.</p><p><strong>Step 3 — Code by example</strong></p><p>I suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns"><strong>git repository “Andreas Poyias”</strong></a> or from the snippets here and paste it in any of the available online C++ editors like <a href="http://cpp.sh/">c++shell</a>, <a href="https://www.jdoodle.com/online-compiler-c++">jdoodle </a>, <a href="https://www.onlinegdb.com/online_c++_compiler">onlineGDB</a> and run it to <strong>observe the output</strong>. Then read the comments or description below.</p><p><strong><em>Class definition</em></strong><em><br></em>I am showing the class definition in C++ which is 8 lines of code.</p><pre><strong>#include</strong> &lt;iostream&gt;</pre><pre><strong>class </strong>Singleton<br>{<br><strong>public:</strong><br>    <strong>static </strong>Singleton *getInstance();<br><strong>private:</strong><br>    Singleton(){}<br>    <strong>static </strong>Singleton* s_instance;<br>};</pre><p>Now we move on to the declaration of the getInstance()method and the static data member which is outside the class definition. There are different ways to write the getInstance function. For simplicity, I chose the one shown in the snippet below. So if the instance does not exist, instantiate one if it does exist then just return it.</p><pre>Singleton* Singleton::s_instance = 0;</pre><pre>Singleton* Singleton::getInstance()<br>{<br>    <strong>if</strong>(!s_instance) {<br>        s_instance = <strong>new </strong>Singleton();<br>        <strong>std::cout </strong>&lt;&lt; &quot;There is no instance so we created one.\n&quot;;<br>        <strong>return </strong>s_instance;<br>    }<strong>else</strong>{<br>        <strong>std::cout </strong>&lt;&lt; &quot;Hey this is the same instance!\n&quot;;<br>      <strong>return </strong>s_instance;<br>    }<br>}</pre><p><strong><em>Main function</em></strong><em><br></em>The main function operates as the <strong>client</strong>. The client cannot create a second instance of theSingletonclass and is forced to use the existing one. This can be displayed by the output as well.</p><pre><strong>int </strong>main()<br>{<br> Singleton *singlA = Singleton::getInstance();<br> Singleton *singlB = Singleton::getInstance();<br> <strong>return </strong>0;<br>}</pre><pre><strong>//</strong> <strong>Output</strong><br>// There is no instance so we created one.<br>// Hey this is the same instance!</pre><p>There are a few <strong>benefits </strong>for the use of Singleton pattern. Other design patterns like Abstract Factory, Facade can use Singleton pattern (usually only one Facade object is required). As I mentioned in the first paragraph this design pattern is quite controversial and that is why a popular interview question is: <strong>“what is wrong with Singleton pattern, or why is Singleton pattern considered anti-pattern?”</strong></p><p><strong>Anti-pattern<br></strong>I will summarise the reasons why singleton is considered anti-pattern. There is a very popular <a href="https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons">discussion</a> on StackOverflow which provides really good justice justifying why one should be careful with this design pattern.</p><ol><li>Singleton patterns violate the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle</a>: by virtue of the fact that they control their own creation and lifecycle.</li><li>They are generally used as a global instance which may lead to hidden dependencies in the code that could be exposed via interfaces.</li><li>They inherently cause code to be tightly <a href="https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29">coupled</a>.</li><li>It is very difficult to adjust Singleton pattern in a multithreading environment and very easy to fall into race condition problems during initialization.</li></ol><p>For deeper understanding as to why this is considered anti-pattern, have a look in this <a href="https://www.michaelsafyan.com/tech/design/patterns/singleton">site by Michael Safyan</a>.</p><p>Since we mentioned it above, the next blog will be a quick guide to the <strong>Facade </strong>design pattern. The Facade<strong> </strong>is not a creational pattern like Singleton and <a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Abstract Factory</a> but is classified as a <strong>structural design pattern</strong>. Don’t forget to like/clap my blog-post and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60732ed43956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — A quick guide to Abstract Factory.]]></title>
            <link>https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c?source=rss-ad8b7380b7ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab500dc12e6c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[abstract-factory]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Andreas Poyias]]></dc:creator>
            <pubDate>Mon, 10 Dec 2018 19:01:00 GMT</pubDate>
            <atom:updated>2019-02-08T15:25:58.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns — A quick guide to Abstract Factory.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUrJ_zstaju8BDwHmeOHvg.jpeg" /></figure><p>This is a quick-guide to mastering one of the most commonly used design patterns, the <strong>Abstract Factory</strong>. Even though the coding examples will be in <strong>C++</strong> as I am more comfortable with, they can be easily adjusted to any programming language like <strong>Java, Python, C#, Javascript </strong>and more.</p><blockquote><strong>Abstract Factory</strong> is classified in the <strong><em>creational</em></strong><em> design patterns</em> which is all about class/object instantiation. More precisely, how to effectively use inheritance (class-creation patterns) or delegation (object-creation patterns). [by <a href="https://sourcemaking.com/design-patterns-ebook">Design Patterns explained simply</a>]</blockquote><p><strong>Factory definition</strong>: <em>“It is a building or group of buildings where </em><strong><em>products</em></strong><em> are manufactured/</em><strong><em>created</em></strong><em>”.</em><strong> </strong>Products are then being sent to the clients for use at their own responsibility. At the same time, the factory clients are many, it should be fairly easy for the clients to order their product and similarly easy for the factory to adapt according to the client’s needs.</p><p>Let’s connect the dots to understanding this design pattern. We use it when we need an interface for the <strong>creation </strong>of dependent objects without necessarily specifying their concrete classes. At the same time, we want to <strong>encapsulate </strong>the construction of “products” using <strong>inheritance</strong>.</p><p><strong>Step 1 — Keywords</strong></p><p>Defining <strong>keywords </strong>is the secret recipe in this series of quick-guides. This method helped me truly understand the design patterns, hardcode them in my mind and comprehend the differences among other design patterns.</p><ol><li><strong>Product</strong>: It is an object built by a factory and it is included in a family of objects. It is very specific as there is no abstraction to it. <em>Example: BMWdoorHandle, FordDoorHandle.</em></li><li><strong>Abstract Product</strong>: It is a higher level view of a product which defines its family. <em>Example DoorHandle, DoorWindow</em></li><li><strong>Concrete Factory</strong>: It is a factory that is “physically” micro-managing the creation and completion of a product. <em>Example: BMWFactory, FordFactory.</em></li><li><strong>Abstract Factory</strong>: Is an interface for creating families of related or dependent objects without specifying their concrete classes. <em>Example: CarFactory</em></li></ol><p><strong>Step 2 —Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*clFtLeD_H95m7ZFPnBDScQ.png" /></figure><p>When discussing <strong>Abstract Factory</strong> everything should be relevant to the keywords above. If the code starts to diverge from those words then probably something isn’t quite right. Let’s make this simple, <strong>Concrete Factory</strong> is inheriting from <strong>Abstract Factory</strong> and <strong>Product</strong> from <strong>Abstract Product</strong>. The diagram is as plain as it looks; two classes inheriting from their abstract classes. The concrete factory is the one to do the dirty work to <strong>create</strong> specific Products (which is identified by the red line). Now with this diagram, it is easy to understand that this design pattern can easily be updated by adding more concrete factories and more products i.e. ProductC, ProductD etc. In other words, this picture can only grow wider and definitely not in height.</p><p><strong>Step 3 — Code by example</strong></p><p>I would suggest to copy the code class by class from my <a href="https://github.com/Poyias/DesignPatterns/blob/master/AbstractFactory.cpp"><strong>git repository “Andreas Poyias”</strong></a> and paste it in any online C++ editor like <a href="http://cpp.sh/"><strong>c++shell</strong></a><strong>, </strong><a href="https://www.jdoodle.com/online-compiler-c++"><strong>jdoodle </strong></a>or <a href="https://www.onlinegdb.com/online_c++_compiler"><strong>onlineGDB</strong></a> or any other and run it to observe the output. Then read the comments or description below. The class names are written such that after the underscore I give the keyword related to it.</p><p><strong><em>AbstractProduct</em></strong><em><br></em>The abstract product is an abstract class and as expected it defines a family of products that inherit from it. In this example, the abstract product is aDoorHandle, I added a function that prints something for the purposes of showcasing.</p><pre><strong>#include</strong> &lt;iostream&gt;</pre><pre><strong>class </strong>DoorHandle_AbstractProduct<br>{<br><strong>public</strong>:<br> // A dummy function that prints something<br> <strong>virtual void </strong>printSerialNumber() = 0;<br>};</pre><p><strong><em>Product</em></strong><br>In this example, the products are BMW or Ford door handle. They have different serial numbers, therefore, each class can print their own product-specific serial number. We could also have DoorWindoworSteeringWheel. The door handle classes inherit from the abstract class above.</p><pre>// BMW door handle [in the family of doorHandles]<br><strong>class </strong>BMWDoorHandle_Product : <strong>public </strong>DoorHandle_AbstractProduct <br>{<br><strong>public</strong>:<br>    // Prints product-specific serial number<br>    <strong>void </strong>printSerialNumber (){<br>        <strong>std::cout</strong> &lt;&lt; &quot; DoorHandle_Product: BMW123 \n&quot;;<br>    }<br>};</pre><pre>// Ford door handle [in the family of doorHandles]<br><strong>class </strong>FordDoorHandle_Product : <strong>public </strong>DoorHandle_AbstractProduct <br>{<br><strong>public</strong>:<br>    // Prints product-specific serial number<br>    <strong>void </strong>printSerialNumber (){<br>        <strong>std::cout</strong> &lt;&lt; &quot; DoorHandle_Product: Ford123 \n&quot;;<br>    }<br>};</pre><p><strong><em>AbstracFactory</em></strong><em><br></em> This is a very generic/abstract class which should not have much more than the createfunctions. In the end, a factory is just creating products.</p><pre><strong>class </strong>Car_AbstractFactory <br>{<br><strong>public</strong>:<br> <strong>virtual </strong>DoorHandle_AbstractProduct* createDoorHandle () = 0;<br> //virtual DoorWindow_AbstractProduct* createDoorWindow () = 0;<br>};</pre><p><strong><em>ConcreteFactory</em></strong><br>This factory class is quite specific to the product. It is the hard worker that puts the puzzle together. In this example, it is specific to a brand {BMW, Ford}. Its job is to return an instance of a product which is specific to that brand. Again, if we wanted to createBMWDoorWindow we could actually create a new function that returns an instance of the relevant abstract class. In my <a href="https://github.com/Poyias/DesignPatterns/blob/master/AbstractFactory.cpp"><strong>git</strong> repository</a>, there is the full implementation with theDoorWindow parts as well.</p><pre><strong>class </strong>BMWCar_ConcreteFactory : <strong>public </strong>Car_AbstractFactory <br>{<br><strong>public</strong>:<br>    DoorHandle_AbstractProduct* createDoorHandle (){<br>        <strong>return new </strong>BMWDoorHandle_Product;<br>    }<br>};</pre><pre><strong>class </strong>FordCar_ConcreteFactory : <strong>public </strong>Car_AbstractFactory <br>{<br><strong>public</strong>:<br>    DoorHandle_AbstractProduct* createDoorHandle (){<br>        <strong>return new </strong>FordDoorHandle_Product;<br>    }<br>};</pre><p><strong><em>Main function</em></strong><em><br></em>Finally, this is the last piece of code. The main function which operates as the <strong>client</strong>. The client can easily “order” products from the factory and can use them in any way he likes.</p><pre><strong>int </strong>main()<br>{<br>    // Client needs a doorHandle and a doorWindow<br>    <strong>Car_AbstractFactory*</strong> abstractFactory;<br>   <strong> DoorHandle_AbstractProduct*</strong> dHandle_AbstractProduct;<br> <br>    // The client needs products from Ford brand<br>    abstractFactory = <strong>new </strong>FordCar_ConcreteFactory;</pre><pre>    // Ford concrete factory creates them <br>    // and returns them to the client<br>    dHandle_AbstractProduct = abstractFactory-&gt;createDoorHandle();</pre><pre>    // Client uses the products<br>    dHandle_AbstractProduct -&gt; printSerialNumber();</pre><pre>    // Now the client wants products but from BMW brand<br>    abstractFactory = new BMWCar_ConcreteFactory;</pre><pre>    // So the BMW concrete factory creates them <br>    // and returns them to the client<br>    dHandle_AbstractProduct = abstractFactory-&gt;createDoorHandle();</pre><pre>    // Client uses the products<br>    dHandle_AbstractProduct -&gt; printSerialNumber();</pre><pre><strong>return </strong>0;<br>}</pre><pre><strong>// Output<br></strong>// DoorHandle_Product: Ford123   <br>// DoorHandle_Product: BMW123</pre><p><strong>Benefits </strong>might not be instantly obvious. But imagine for a second how many products a car has and how many things can a car factory do. Now imagine the chaos maintaining a badly designed code every time BMW decides to alter a door handle. Add a new type of driver-seat or even change something in the engine. Now adding to the complexity, imagine maintaining these problems but for multiple brands. Abstract factory offers a maintainable and clean approach, that can be used for years to come. It would be difficult for a new developer to mess up and so easy to add/remove a new product.</p><p>Abstract factory is just the beginning of this journey. This is one of the most commonly used design patterns and many times it is used in combination with other design patterns. The next blog will be a quick-guide to <strong>Singleton design pattern</strong>. Don’t forget to like my blog and follow my account. This is to give me the satisfaction that I helped some fellow developers and push me to keep on writing.</p><p><strong>Other quick-guides on design patterns:</strong></p><ol><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-abstract-factory-ab500dc12e6c">Design Patterns — A quick guide to <strong>Abstract Factory</strong>.</a></li><li><a href="https://blog.usejournal.com/design-patterns-a-quick-guide-to-bridge-pattern-9ebf6a77baed">Design Patterns — A quick guide to <strong>Bridge Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-builder-pattern-a834d7cacead">Design Patterns — A quick guide to <strong>Builder Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-decorator-pattern-2159b97863f">Design Patterns — A quick guide to <strong>Decorator</strong> <strong>Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-facade-pattern-16e3d2f1bfb6">Design Patterns — A quick guide to <strong>Facade Pattern</strong>.</a></li><li><a href="https://medium.com/datadriveninvestor/design-patterns-a-quick-guide-to-observer-pattern-d0622145d6c2">Design Patterns — A quick guide to <strong>Observer Pattern</strong>.</a></li><li><a href="https://medium.com/@andreaspoyias/design-patterns-a-quick-guide-to-singleton-pattern-60732ed43956">Design Patterns — A quick guide to <strong>Singleton Pattern</strong>.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab500dc12e6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>