<?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 Piyush Sinha on Medium]]></title>
        <description><![CDATA[Stories by Piyush Sinha on Medium]]></description>
        <link>https://medium.com/@sin-pi0?source=rss-743cc8729c3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y5EKg6YsvEbAuHOp9TfIlA.jpeg</url>
            <title>Stories by Piyush Sinha on Medium</title>
            <link>https://medium.com/@sin-pi0?source=rss-743cc8729c3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:57:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sin-pi0/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[Mac Setup for Coders 2026]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://sin-pi0.medium.com/mac-setup-for-coders-2026-31faf6bf13d4?source=rss-743cc8729c3f------2"><img src="https://cdn-images-1.medium.com/max/800/0*MSTq-QTlMv79VD_c.png" width="800"></a></p><p class="medium-feed-snippet">Install Homebrew</p><p class="medium-feed-link"><a href="https://sin-pi0.medium.com/mac-setup-for-coders-2026-31faf6bf13d4?source=rss-743cc8729c3f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://sin-pi0.medium.com/mac-setup-for-coders-2026-31faf6bf13d4?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31faf6bf13d4</guid>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Sun, 17 May 2026 18:15:02 GMT</pubDate>
            <atom:updated>2026-06-15T16:49:31.339Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Metrics That Get Measured Get Managed: How Continuous Monitoring Drives Success at Boom Games]]></title>
            <link>https://sin-pi0.medium.com/metrics-that-get-measured-get-managed-how-continuous-monitoring-drives-success-at-boom-games-472b2581fe52?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/472b2581fe52</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 22:48:02 GMT</pubDate>
            <atom:updated>2025-03-17T17:54:45.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BbRbtouEM1ge5PpP" /><figcaption>Source: Unsplash</figcaption></figure><p>At <a href="https://boomgames.in/">Boom Games</a>, we understand that the key to delivering a seamless gaming experience lies not just in building great features, but in continuously monitoring every critical metric of the platform. This is especially true in the fast-paced, high-performance environment of <strong>real-money gaming</strong>, where downtime or performance issues can directly affect player satisfaction and the company’s bottom line.</p><p>We firmly believe that <strong>metrics that get measured get managed </strong>(a quote I personally learned from <a href="https://www.youtube.com/@KaranBajajOfficial">Karan Bajaj’s YT videos</a>), which is why we’ve built an extensive system for monitoring, observability, and alerting to ensure that nothing is missed and everything is proactively managed.</p><p>In this article, we’ll walk you through how we apply this principle across our organization, and how monitoring, observability, and alerting systems help us manage game performance, player experience, and system reliability.</p><p><em>Please note that we have just started, and we still have a long way to go.</em></p><h3>1. Continuous Monitoring: The Backbone of Our Operations</h3><p>Our monitoring setup, built on <strong>Prometheus, Grafana, Databricks and Tableau,</strong> continuously tracks, visualizes, and alerts us on key metrics. These metrics help us measure everything from <strong>infrastructure health </strong>(<em>e.g. CPU, memory usage, load distribution</em>) to <strong>application specific performance</strong> (<em>e.g. p99 latencies, throughput, database health) </em>to <strong>business growth indicators </strong>(<em>e.g. total wager, ARPU, Retention</em>).</p><p>Any spike in metrics like <strong>p99 latencies or CPU usage</strong> above a certain threshold (<em>e.g. p99 latencies &gt; 500ms, CPU usage &gt; 80%</em>) triggers an immediate notification via <strong>Slack</strong>.</p><p><strong>Grafana and Tableau dashboards</strong> also provide us with a unified view of all the collected metrics, including comparisons with data from the <strong>previous day, previous week or previous month</strong>, enabling us to spot anomalies quickly.</p><p>For example, if there is a predetermined delta in transaction volume compared to previous day or week (<em>e.g. — 10% decrease in total deposit compared to yesterday</em>), we receive a <strong>Slack alert </strong>which gets escalated to relevant stakeholders to investigate. This alerting system helps us respond to any drop in metrics, such as a sudden decrease in player activity, payment failures, or other potential issues that might otherwise go unnoticed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnKcE7v-Os204WOoIuofSg.png" /><figcaption>Sample Slack Alert For Deviation in Key KPI Metrics</figcaption></figure><h3>2. ELK for APM and Log Monitoring: Tracing Every Request</h3><p>We rely on <strong>ELK</strong> (Elasticsearch, Logstash, and Kibana) for our <strong>Application Performance Monitoring (APM)</strong> and <strong>logs</strong>. ELK provides us with a <strong>centralized</strong> log aggregation system that allows us to filter and analyze logs from all of our services in real-time.</p><p>While we don’t use<strong> Jaeger or OpenTelemetry</strong> for distributed tracing, our logs are intelligently structured to contain <strong>request ID</strong>, <strong>player ID</strong> and <strong>game ID </strong>(<em>game ID is optional, only present in game related APIs and logs</em>).</p><p>Having these unique identifiers in our logs makes it easy to trace the flow of any request across our entire system, significantly speeding up the debugging process.</p><p>Example of an <strong>ELK log entry</strong>:</p><pre>2025-03-16T18:01:33.588Z [Svc-1] [INFO] [01JPG2DC3NYKDBN7260MB6W0BE-xxxxxx(playerId)-123456(gameId)] &lt;log&gt;<br>2025-03-16T18:01:53.802Z [Svc-2] [INFO] [01JPG2DC3NYKDBN7260MB6W0BE-xxxxxx(playerId)-123456(gameId)] &lt;log&gt;<br>2025-03-16T18:02:36.476Z [Svc-3] [ERROR] [01JPG2DC3NYKDBN7260MB6W0BE-xxxxxx(playerId)-123456(gameId)] &lt;log&gt;</pre><p>As you can see, each log entry contains the <strong>request ID</strong>, <strong>player ID</strong>, and <strong>game ID</strong>, providing full context for each request.</p><p>In addition to our ELK system, we ensure that any uncaught service exceptions are asynchronously logged into our database. This backup mechanism ensures that we can still retrieve important logs even if we need to prune logs from ELK due to large volume or retention policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*18xhoozbJ2HNkjgR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/0*rj_CN3OOe_IB6jds.png" /><figcaption>Dummy Sample of our exception log document in database</figcaption></figure><p>We use <strong>ULID</strong> (Universally Unique Lexicographically Sortable Identifier) rather than <strong>UUID</strong> for generating IDs. ULID offers several advantages for our high-transaction gaming environment:</p><ul><li><strong>Chronologically Sortable</strong>: ULID is time-based, allowing us to easily sort logs, events, and transactions in chronological order.</li><li><strong>Efficiency</strong>: Unlike UUIDs, which can have unpredictable ordering, ULID allows us to optimize <strong>database indexing</strong> and <strong>search performance</strong>.</li></ul><h3>3. App Crash Rate Monitoring: Our Commitment to Quality</h3><p>At Boom Games, we take app stability seriously. Our target is to maintain an <strong>app crash rate of less than 0.5%</strong> in every release. Here’s how we ensure that:</p><ul><li><strong>Crash Detection</strong>: We use <strong>Firebase Crashlytics </strong>to capture app crashes. It allows us to monitor crash rates along with the impact, device logs and version in which the crash got introduced.</li><li><strong>Quality Gates</strong>: We gradually roll out the app in steps of 10 percentage points, rather than releasing it to 100% of players at once. If the crash rate exceeds 0.5%, the release is blocked, preventing any widespread impact on our players.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*-B1_hLQhGAMm70IL.png" /><figcaption>Crash Rate For Our Last App Release</figcaption></figure><h3>4. Proactive Monitoring For Async Jobs</h3><p>To ensure that all the asynchronous workflows like <strong>leaderboard updates, rewards for challenge completion, loyalty upgrades</strong> etc are processed reliably, we have set up a robust monitoring and alerting system. This system helps us detect any failures or delays in these processes in real-time.</p><p>The tech team receives <strong>Slack alerts</strong> whenever a scheduled task starts and completes. If there is any error or delay, an alert is sent immediately, ensuring that the issue is addressed promptly and minimizing any impact on the player experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QTcNbB-Z-Ywvxvnm.png" /><figcaption>Sample Alert for Leaderboard Rank Updates</figcaption></figure><h3>5. Automated Fraud Detection: Enhancing Operational Efficiency</h3><p>At Boom Games, fraud prevention is a top priority. To ensure the safety of both players and the platform, we’ve implemented an <strong>automated fraud detection </strong>that evaluates multiple parameters, like <strong>device match</strong>, <strong>referral patterns etc</strong>, assigning a <strong>fraud score</strong> to identify and flag suspicious activity for further review.</p><p>If a player is marked as <strong>suspicious</strong>, our automated system <strong>blocks withdrawals</strong> and restricts certain account actions until further verification is done. This helps prevent fraudulent withdrawals and ensures that only legitimate transactions are processed, protecting both players and the company from financial losses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pX6VMdRBg9gyAV3s.png" /><figcaption>Sample Fraud Alert</figcaption></figure><h3>6. Data Accuracy: Monitoring Data Lake &amp; Production Database</h3><p>Our game and player data is crucial for our operations, and we take its accuracy seriously. We monitor both our <strong>data lake</strong> (used for analytics) and <strong>production databases</strong> to ensure the consistency and reliability of data.</p><p>We have a daily automated process that sends us a <strong>Slack alert</strong> to verify the accuracy of data flowing from our production databases into the data lake (<em>e.g. — total wager, game count etc</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*gbNTpp90sE7UKSEi.png" /><figcaption>Sample alert for Data Lake Accuracy</figcaption></figure><h3>7. Last but not the least — Daily Metric and KPI Review Call</h3><p>Finally, we conduct a <strong>daily 1-hour review call </strong>with all relevant stakeholders to stay ahead of any potential issues. Some of the key metrics we track include:</p><ul><li><strong>OTP Delivery Success Rate</strong></li><li><strong>KYC Initiation to Completion Rate</strong></li><li><strong>Game Join to Completion Rate</strong></li><li><strong>Payment Success Rate</strong></li><li><strong>Signup to FTD (First Time Deposit) Rate</strong></li></ul><p>… and more than <strong>50+ other metrics</strong> that help us ensure the platform runs smoothly and identify any trends or problems before they impact the player experience.</p><h3>Future Roadmap</h3><ul><li>Integrate with <strong>Sentry</strong> for our frontend logs.</li><li>Predict traffic patterns and dynamically scale instances up or down to optimize <strong>infrastructure costs</strong>.</li><li>Enhance our <strong>fraud detection framework</strong>.</li><li>Integrate with <strong>AI tools and agents</strong> to automate most of the mundane and routine day-to-day tasks.</li><li><strong>Attempt to break world record for world’s largest online Rummy tournament</strong> 🤞</li></ul><p>We are constantly evolving our processes and systems to improve, and we’d love to hear your thoughts. Do you have any suggestions or ideas for enhancing our monitoring and observability systems? Let us know!</p><p>We are always looking for great talent who are passionate about joining a challenger brand and making an impact in an industry dominated by giants. If you’re ready to break out and innovate, come join us! <strong>DM me over </strong><a href="https://www.linkedin.com/in/sin-pi0/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472b2581fe52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying HTTPS: How Your Web Connection Becomes Super Secure]]></title>
            <link>https://sin-pi0.medium.com/demystifying-https-how-your-web-connection-becomes-super-secure-4c9173159c50?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9173159c50</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 20:20:32 GMT</pubDate>
            <atom:updated>2023-07-08T20:20:32.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TkUij_8Mhdk2cNc7W1TrA.jpeg" /></figure><p>In this digital age, where our personal information is often at stake, ensuring secure online connections is crucial. That’s where <strong>HTTPS</strong> (Hypertext Transfer Protocol Secure) comes into play.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*BDc7_kzNpI2gEMAX8MjzOQ.png" /></figure><p>You might have seen that little lock icon in your browser’s address bar, indicating a secure connection. But have you ever wondered how HTTPS works and what happens behind the scenes during a TLS handshake? In this article, we’ll take you on an exciting journey into the world of HTTPS and unravel the magic of the TLS handshake.</p><h4>Understanding HTTPS: Protecting Your Data Like a Boss!</h4><p>HTTPS is like a guardian angel that keeps your online communication confidential and tamper-proof. It stands for Hypertext Transfer Protocol Secure, and it’s an enhanced version of the standard HTTP protocol. The “S” in HTTPS refers to “Secure,” emphasizing the encryption and security measures it employs. It’s like wrapping your data in a secure bubble before sending it across the web.</p><h4>Meet TLS: The Unsung Hero of HTTPS</h4><p>At the heart of HTTPS lies Transport Layer Security (TLS). TLS is a cryptographic protocol that ensures the security of your data during transmission. It does this by providing three essential services: <strong>encryption</strong>, <strong>authentication</strong>, and <strong>data integrity</strong>. Think of TLS as a superhero cape that shields your sensitive information from prying eyes and ensures it reaches its destination safely.</p><h4>The Thrilling TLS Handshake: How the Magic Happens</h4><p><strong>#1 Client Hello</strong>: The client (your browser) initiates the TLS handshake by sending a friendly “Hello” message to the server. This message includes the supported TLS versions, encryption algorithms, and other parameters. It also generates a random number called the ‘client random.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*L2G2Q7NqwH90b1AGMZ76xw.png" /></figure><p><strong>#2 Server Hello</strong>: The server responds with its own “Hello” message, welcoming the client into the secure club. This message contains the selected TLS version, encryption algorithm, and server-generated random number called the ‘server random.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*JxsotDzW_xQq1emDTV6bog.png" /></figure><p><strong>#3 Certificate Exchange</strong>: The server shows its identification card, known as a digital certificate, to the client. The certificate contains the server’s public key, which the client uses to establish a secure connection. The client verifies the certificate’s authenticity and checks if it trusts the certificate authority (CA) that issued it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*bV6balhWlDpjE0BtWKYJCg.png" /></figure><p><strong>#4 Key Exchange</strong>: The client generates a secret code, called a “pre-master secret,” and encrypts it using the server’s public key. Only the server, with its special private key, can unlock this secret message. It’s like sharing a secret code only known to the two of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*fg50UF3IoH6XpZt1a0uRnA.png" /></figure><p><strong>#5 Session Key Generation</strong>: Both the client and the server create session keys from the shared secret code and the client and server random numbers. These session keys are used for symmetric encryption and decryption of the data transmitted during the session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*gUSDC_gQbXBm8O514rdY6g.png" /></figure><p><strong>#6 Change Cipher Spec</strong>: It’s showtime! Both the client and the server notify each other to switch to the newly established secure connection by exchanging ‘Change Cipher Spec’ messages. From this point onwards, all data transmitted will be encrypted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*-xr-t19oZ2UZ_pPUBzpQKw.png" /></figure><p><strong>#7 Handshake Completion</strong>: To seal the deal, the client and server exchange “Finished” messages. These messages contain a hash of all the previous handshake messages, ensuring that nothing got tampered with along the way. If the hashes match, it’s like a virtual handshake, and the secure connection is established.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Al9wfa41wHzaXJ8SgOqPvA.png" /></figure><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Jaf7lanGSekJSEXOpqJSDA.png" /></figure><p>Congratulations! You now have a backstage pass to the world of HTTPS and the thrilling TLS handshake. With HTTPS and TLS working together, your online interactions are safer than ever.</p><p>So, the next time you see that little lock icon in your browser, remember the magic that happens behind the scenes to keep your data secure. Stay safe and surf the web with confidence!</p><h4>References:</h4><ul><li>IETF. (2008). RFC 5246 — The Transport Layer Security (TLS) Protocol Version 1.2. Retrieved from <a href="https://tools.ietf.org/html/rfc5246">https://tools.ietf.org/html/rfc5246</a></li><li>Mozilla. (n.d.). How HTTPS Works. Retrieved from <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview#http_and_https">https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview#http_and_https</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9173159c50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 6. Being Adaptive: the Adapter and Facade Patterns]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6361a602c3a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 15:08:13 GMT</pubDate>
            <atom:updated>2023-07-06T19:27:25.318Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 7. Being Adaptive: the Adapter and Facade Patterns</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*UTIxzUBgQKrKe8wa.jpg" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><a href="https://faun.pub/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><a href="https://faun.pub/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><strong>Being Adaptive: the Adapter and Facade Patterns</strong></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4>Problem Statement 1:</h4><ul><li>We have a simplified version of the Duck interfaces and classes:</li></ul><pre>type duck interface {<br>   quack()<br>   fly()<br>}</pre><ul><li>Here’s a subclass of Duck, the MallardDuck</li></ul><pre>type mallardDuck struct{}<br><br>func (m *mallardDuck) quack()  {<br>   fmt.Println(&quot;Quack&quot;)<br>}<br><br>func (m *mallardDuck) fly()  {<br>   fmt.Println(&quot;I&#39;m flying&quot;)<br>}</pre><ul><li>There’s a new fowl on the block: Turkey. They don’t quack, they gobble.</li></ul><pre>type turkey interface {<br>   gobble()<br>   fly()<br>}</pre><pre>type wildTurkey struct {}<br><br>func (w *wildTurkey) gobble()  {<br>   fmt.Println(&quot;Gobble Gobble&quot;)<br>}<br><br>func (w *wildTurkey) fly()  {<br>   fmt.Println(&quot;I&#39;m flying a short distance&quot;)<br>}</pre><ul><li>We are short on Duck objects and we would like to use some Turkey objects in their place. Obviously we can’t use the turkeys outright because they have a different interface.</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>In cases wherein we don’t want to change the vendor code (in this case Turkey interface), we can write a class that adapts the new the vendor interface into the one we are expecting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*PwslTy9cJi19fG66wJOpmA.png" /></figure><ul><li>Let’s see how an adapter for Turkey looks like:</li></ul><pre><strong><em>/**<br> * We need to get a reference to the<br> * object we are adapting.<br> */</em></strong><br>type turkeyAdapter struct {<br>   turkey turkey<br>}<br><br>func newTurkeyAdapter(t turkey) *turkeyAdapter {<br>   return &amp;turkeyAdapter{<br>      turkey: t,<br>   }<br>}<br><br><strong><em>/**<br> * Implement the interface of the<br> * type you’re adapting to. This is the<br> * interface your client expects to see<br> */</em></strong><br>func (t *turkeyAdapter) quack() {<br>   t.turkey.gobble()<br>}<br><br>func (t *turkeyAdapter) fly() {<br>   for i := 1; i &lt;= 5; i++ {<br>      t.turkey.fly()<br>   }<br>}</pre><ul><li>Test drive the adapter</li></ul><pre>func main() {<br>   <strong><em>// Creating a duck and a turkey</em></strong><br>   mallardDuck := &amp;mallardDuck{}<br><br>   wildTurkey := &amp;wildTurkey{}<br><br>  <strong><em> // Wrapping the turkey in a turkey adapter, which makes it look like a duck</em></strong><br>   turkeyAdapter := newTurkeyAdaptor(wildTurkey)<br><br>   <strong><em>// Passing the duck to a method testDuck() which expects a Duck object</em></strong><br>   fmt.Println(&quot;The Duck says...&quot;)<br>   testDuck(mallardDuck)<br><br>   <strong><em>// Passing off Turkey as a Duck to the same method</em></strong><br>   fmt.Println(&quot;\nThe Turkey Adapter says...&quot;)<br>   testDuck(turkeyAdapter)<br>}<br><br>func testDuck(d duck) {<br>   d.quack()<br>   d.fly()<br>}</pre><ul><li>Result</li></ul><pre>The Duck says...<br>Quack<br>I&#39;m flying</pre><pre>The Turkey Adapter says...<br>Gobble Gobble<br>I&#39;m flying a short distance<br>I&#39;m flying a short distance<br>I&#39;m flying a short distance<br>I&#39;m flying a short distance<br>I&#39;m flying a short distance</pre><ul><li>This is called an <strong>Adapter Pattern.</strong></li><li>Wiki Definition: The <strong>Adapter Pattern</strong> converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMyxpYnIjNLbtHjjr2Kf_w.png" /></figure><ul><li>We’ve seen how the Adapter Pattern converts the interface into one that a client is expecting. We also know we achieve this by wrapping the object that has an incompatible interface with an object that implements the correct one.</li><li>We’re going to look at a pattern now that alters an interface, but for a different reason: to simplify the interface. It’s aptly named the <strong>Facade</strong> <strong>Pattern</strong> because this pattern hides all the complexity of one or more classes behind a clean, well-lit facade.</li></ul><h4>Problem Statement 2:</h4><ul><li>Build a home theater system.</li><li>It’s a system complete with a DVD player, a projection video system, an automated screen, surround sound and even a popcorn popper.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou6qmgJE3IAJmTynsDKQjQ.png" /></figure><ul><li>To watch a movie, we need to perform a few tasks:</li></ul><ol><li>Turn on the popcorn popper</li><li>Start the popper popping</li><li>Dim the lights</li><li>Put the screen down</li><li>Turn the projector on</li><li>Put the projector on wide-screen mode</li><li>Turn the sound amplifier on</li><li>Set the amplifier to surround sound</li><li>Set the amplifier volume to medium (5)</li><li>Turn the DVD Player on</li><li>Start the DVD Player playing</li></ol><ul><li>Let’s see in terms of classes and method calls needed to perform them</li></ul><pre>popper.on()<br>popper.pop()</pre><pre>lights.dim(10)</pre><pre>screen.down()</pre><pre>projector.on()<br>projector.wideScreenMode()</pre><pre>amp.on()<br>amp.setSurroundSound()<br>amp.setVolume(5)</pre><pre>dvd.on()<br>dvd.play(movie)</pre><ul><li>And there’s more… When the movie is over, we have to turn everything off.</li><li>If we upgrade the system, there can different procedures.</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>A Facade is just what we need; with the <strong>Facade Pattern</strong>, we can take a complex subsystem and make it easier to use by implementing a Facade class that provides one, more readable interface. It allows us to avoid tight coupling between clients and subsystems.</li><li>Wiki Definition: The <strong>Facade Pattern</strong> provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.</li><li>Let’s take a look at how the Facade operates:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLas4efF7QW4DYHKUbWnUg.png" /></figure><ul><li>What’s the benefit of the facade other than the fact that I now have a simpler interface? — The Facade Pattern also allows you to decouple your client implementation from any one subsystem.</li><li>Let’s say for instance that you get a big raise and decide to upgrade your home theater to all new components that have different interfaces. Well, if you coded your client to the facade rather than the subsystem, your client code doesn’t need to change, just the facade.</li><li>Let’s dig into some code</li><li>Constructing the home theater facade</li></ul><pre><strong><em>/**<br> * Here is the composition;<br> * these are all the components of the<br> * subsystem we are going to use<br> */</em></strong><br>type homeTheaterFacade struct {<br>   amp    *amplifier<br>   dvd    *dvdPlayer<br>   proj   *projector<br>   lights *theaterLights<br>   screen *screen<br>   popper *popcornPopper<br>}<br><br><strong><em>/**<br> * Instantiating all the components of the subsystem<br> */</em></strong><br>func newHomeTheaterFacade() *homeTheaterFacade {<br>   return &amp;homeTheaterFacade{<br>      amp:    &amp;amplifier{},<br>      dvd:    &amp;dvdPlayer{},<br>      proj:   &amp;projector{},<br>      lights: &amp;theaterLights{},<br>      screen: &amp;screen{},<br>      popper: &amp;popcornPopper{},<br>   }<br>}</pre><ul><li>Implementing the simplified interfaces</li></ul><pre><strong><em>/**<br> * watchMovie() follows the same sequence<br> * we had to do by hand before, but wraps<br> * it up in a handy method that does all<br> * the work. Notice that for each task we<br> * are delegating the responsibility to the<br> * corresponding component in the subsystem.<br> */</em></strong><br>func (h *homeTheaterFacade) watchMovie(movie string) {<br>   fmt.Println(&quot;Get ready to watch a movie...&quot;)<br>   h.popper.on()<br>   h.popper.pop()<br>   h.lights.dim(10)<br>   h.screen.down()<br>   h.proj.on()<br>   h.proj.wideScreenMode()<br>   h.amp.on()<br>   h.amp.setSurroundSound()<br>   h.amp.setVolume(5)<br>   h.dvd.on()<br>   h.dvd.play(movie)<br>}<br><br><strong><em>/**<br> * endMovie() takes care<br> * of shutting everything down<br> * for us. Again, each task is<br> * delegated to the appropriate<br> * component in the subsystem.<br> */</em></strong><br>func (h *homeTheaterFacade) endMovie() {<br>   fmt.Println(&quot;\nShutting movie theater down...&quot;)<br>   h.popper.off()<br>   h.lights.on()<br>   h.screen.up()<br>   h.proj.off()<br>   h.amp.off()<br>   h.dvd.stop()<br>   h.dvd.eject()<br>   h.dvd.off()<br>}</pre><ul><li>Time to watch a movie!</li></ul><pre>func main() {<br>   homeTheater := newHomeTheaterFacade()<br><br>   homeTheater.watchMovie(&quot;Raiders of the Lost Ark&quot;)<br>   homeTheater.endMovie()<br>}</pre><ul><li>Run the code!</li></ul><pre>Get ready to watch a movie...<br>Popcorn Popper on<br>Popcorn Popper popping popcorn!<br>Theater Ceiling Lights dimming to 10%<br>Theater Screen going down<br>Top-O-Line Projector on<br>Top-O-Line Projector in widescreen mode (16x9 aspect ratio)<br>Top-O-Line Amplifier on<br>Top-O-Line Amplifier surround sound on (5 speakers, 1 subwoofer)<br>Top-O-Line Amplifier setting volume to 5<br>Top-O-Line DVD Player on<br>Top-O-Line DVD Player playing &quot;Raiders of the Lost Ark&quot;</pre><pre>Shutting movie theater down...<br>Popcorn Popper off<br>Theater Ceiling Lights on<br>Theater Screen going up<br>Top-O-Line Projector off<br>Top-O-Line Amplifier off<br>Top-O-Line DVD Player stopped<br>Top-O-Line DVD Player eject<br>Top-O-Line DVD Player off</pre><h4>BIG PICTURE</h4><ul><li><strong>Use the Adapter pattern</strong> <strong>when you want to use some existing class, but its interface isn’t compatible with the rest of your code.</strong></li></ul><p>The Adapter pattern lets you create a middle-layer class that serves as a translator between your code and a legacy class, a 3rd-party class or any other class with a weird interface.</p><ul><li><strong>Use the Facade pattern when you need to have a limited but straightforward interface to a complex subsystem.</strong></li></ul><p>Often, subsystems get more complex over time. Even applying design patterns typically leads to creating more classes. A subsystem may become more flexible and easier to reuse in various contexts, but the amount of configuration and boilerplate code it demands from a client grows ever larger. The Facade attempts to fix this problem by providing a shortcut to the most-used features of the subsystem which fit most client requirements.</p><ul><li><strong>Use the Facade when you want to structure a subsystem into layers.</strong></li></ul><p>Create facades to define entry points to each level of a subsystem. You can reduce coupling between multiple subsystems by requiring them to communicate only through facades.</p><p><em>Next : Encapsulating Algorithms: the Template Method Pattern</em></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6361a602c3a" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Head First Design Patterns using Go — 6. Being Adaptive: the Adapter and Facade Patterns</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 5. Encapsulating Invocation: the Command Pattern]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8c0a79d1c7</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Mon, 24 May 2021 20:55:37 GMT</pubDate>
            <atom:updated>2023-07-06T19:26:47.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 6. Encapsulating Invocation: the Command Pattern</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h2dL26gBB6YHW33F.jpg" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><a href="https://faun.pub/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><strong>Encapsulating Invocation: the Command Pattern</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4>Problem Statement 1:</h4><ul><li><strong>Design the Home Automation Remote Control.</strong></li><li>The remote consists of 7 programmable slots (each can be assigned to a different household device) along with corresponding on/off buttons for each.</li><li>Enclosed will be a set of APIs that is created by various vendors to control home automation devices such as lights, fans, audio equipments etc.</li><li>Note that it is important that we be able to control any future devices that the vendors may supply.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*ZnNgosRcNCA9zbEpy5J6bg.png" /><figcaption>The Remote Control</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*WoZGz0ye-LQ4Xrmp_9b1Zg.png" /><figcaption>Vendor Classes</figcaption></figure><h4>Problem Statement 2:</h4><ul><li>Seems like not a lot of thought has been given to come up with a set of common interfaces by the vendors.</li><li>We don’t want the remote to have to know the specifics of the vendor classes.</li><li>We don’t either want the remote to consist of a set of if statements, like “if slot1 == Light, then light.on(), else if slot1 = Hottub then hottub.jetsOn()”</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>Decouple the requester of an action from the object that actually performs the action.</li><li>Here the requester would be the remote control and the object that performs the action would be an instance of one of the vendor class.</li><li>We can decouple them by introducing “<strong>command</strong>” objects into our design. <strong>A command object encapsulates a request to do something (like turn on a light) on a specific object (say, the living room light object). So, if we store a command object for each button, when the button is pressed we ask the command object to do some work.</strong></li><li>The remote doesn’t have any idea what the work is, it just has a command object that knows how to talk to the right object to get the work done. So, you see, the remote is decoupled from the light object!</li><li>This pattern is called <strong>Command Pattern</strong></li><li>Wiki Definition: The <strong>Command Pattern</strong> encapsulates a request as an object, thereby letting you parameterise other objects with different requests, queue or log requests, and support undoable operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Po2vSYNtDC856y-BYkOxYg.png" /></figure><ul><li>Let’s dig into some code to understand this</li></ul><ol><li><strong><em>Implementing the command interface</em></strong></li></ol><pre>type iCommand interface {<br>   execute()<br>}</pre><p>2. <strong><em>Implementing a Command to turn a light on</em></strong></p><p>Remember the Light class has two methods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*cL9liHrKyl3avqmDs1wSBw.png" /></figure><pre>type lightOnCommand struct {<br>   light *light<br>}<br><br><strong><em>/**<br> * The constructor is passed the specific<br> * light that this command is going to<br> * control - say the living room light<br> * - and stashes it in the light instance<br> * variable. When execute gets called, this<br> * is the light object that is going to be<br> * the Receiver of the request.<br> */</em></strong><br>func newLightOnCommand(l *light) *lightOnCommand {<br>   return &amp;lightOnCommand{<br>      light: l,<br>   }<br>}<br><br><strong><em>/**<br> * The execute method calls the<br> * on() method on the receiving<br> * object, which is the light we<br> * are controlling<br> */</em></strong><br>func (l *lightOnCommand) execute() {<br>   l.light.on()<br>}</pre><p>3. <strong><em>Using the command object</em></strong></p><p>Imagine we have a remote control with only one button and corresponding slot to hold a device to control</p><pre>type simpleRemoteControl struct {<br>   slot iCommand<br>}<br><br><strong><em>/**<br> * We have a method for setting<br> * the command the slot is going<br> * to control. This could be called<br> * multiple times if the client of<br> * this code wanted to change the<br> * behaviour of the remote button.<br> */</em></strong><br>func (r *simpleRemoteControl) setCommand(command iCommand) {<br>   r.slot = command<br>}<br><br><strong><em>/**<br> * This method is called when the<br> * button is pressed. All we do is take<br> * the current command bound to the<br> * slot and call its execute() method.<br> */</em></strong><br>func (r *simpleRemoteControl) buttonWasPressed() {<br>   r.slot.execute()<br>}</pre><p>4. <strong><em>Testing the simple remote control</em></strong></p><pre>func main() {<br>  <em> </em><strong><em>/**<br>    * The remote is our Invoker;<br>    * it will be passed a<br>    * command object that can<br>    * be used to make requests.<br>    */</em></strong><br>   remoteControl := &amp;simpleRemoteControl{}<br><br>  <strong><em> /**<br>    * Now we create a Light<br>    * object, this will be the<br>    * Receiver of the request<br>    */</em></strong><br>   light := &amp;light{}<br><br>   <strong><em>/**<br>    * Create a command and<br>    * pass the Receiver to it.<br>    */</em></strong><br>   lightOnCommand := newLightOnCommand(light)<br><br>   <strong><em>/**<br>    * Pass the command to the Invoker<br>    */</em></strong><br>   remoteControl.setCommand(lightOnCommand)<br><br>   <strong><em>/**<br>    * We simulate the button being pressed.<br>    */</em></strong><br>   remoteControl.buttonWasPressed()<br>}</pre><p>5. <strong><em>Output</em></strong></p><pre>Light was turned on</pre><p>6. <strong><em>Taking another command implementation: GarageDoorOpenCommand</em></strong></p><p>The GarageDoor class looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*PVlrN_bUx49vCEkemRTW8A.png" /></figure><p>The <strong>GarageDoorOpenCommand</strong> means we need to <strong><em>up()</em></strong> the GarageDoor and turn the lights on (<strong><em>lightOn()</em></strong>)</p><pre>type garageDoorOpenCommand struct {<br>   garage *garage<br>}<br><br>func newGarageDoorOpenCommand(g *garage) *garageDoorOpenCommand {<br>   return &amp;garageDoorOpenCommand{<br>      garage: g,<br>   }<br>}<br><br>func (g *garageDoorOpenCommand) execute() {<br>   g.garage.up()<br>   g.garage.lightOn()<br>}</pre><p>Now showing the use of setCommand() method wherein we can change the command implementation at runtime</p><pre>func main() {<br>   <br>   remoteControl := &amp;remoteControl{}<br><br>   light := &amp;light{}<br><br>   lightOnCommand := newLightOnCommand(light)<br><br>   remoteControl.setCommand(lightOnCommand)<br><br>   remoteControl.buttonWasPressed()<br><br>   garage := &amp;garage{}<br><br>   garageDoorOpenCommand := newGarageDoorOpenCommand(garage)<br><br>   <strong><em>/**<br>    * Pass the new command to the invoker<br>    */</em></strong><br>   remoteControl.setCommand(garageDoorOpenCommand)<br><br>   remoteControl.buttonWasPressed()<br>}</pre><p>Output:</p><pre>Light was turned on<br>The Garage is open<br>The Garage Lights are on</pre><ul><li>In terms of class diagram</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIj_6CVkKWVpnXl41btx4g.png" /><figcaption>Final UML Diagram</figcaption></figure><h4>Problem Statement 3:</h4><ul><li>We did Simple Remote which had just one slot. We need to assign commands to the slots in the actual remote, each having an “on” and “off” button.</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>Assign commands to the remote something like this:</li></ul><pre>onCommands[0] = onCommand <br>offCommands[0] = offCommand</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*qH-vqxOjRzxQVuaAVnOY0g.png" /></figure><ul><li>Implementing the Remote Control</li></ul><pre><strong><em>/**<br> * the remote is going to<br> * handle seven On and Off commands, which<br> * we’ll hold in corresponding arrays.<br> */</em></strong><br>type remoteControl struct {<br>   onCommands, offCommands []iCommand<br>}<br><br>func newRemoteControl() *remoteControl {<br>   return &amp;remoteControl{<br>      onCommands:  make([]iCommand, 7),<br>      offCommands: make([]iCommand, 7),<br>   }<br>}<br><br><strong><em>/**<br> * The setCommand() method takes a slot position<br> * and an On and Off command to be stored in<br> * that slot. It puts these commands in the on and<br> * off arrays for later use<br> */</em></strong><br>func (r *remoteControl) setCommand(slot int, onCommand, offCommand iCommand) {<br>   r.onCommands[slot] = onCommand<br>   r.offCommands[slot] = offCommand<br>}<br><br>/**<br> * When an On or Off button is<br> * pressed, the hardware takes<br> * care of calling the corresponding<br> * methods onButtonWasPushed() or<br> * offButtonWasPushed().<br> */<br>func (r *remoteControl) onButtonWasPushed(slot int) {<br>   fmt.Println(&quot;*****&quot;)<br>   r.onCommands[slot].execute()<br>   fmt.Println(&quot;*****&quot;)<br>}<br><br>func (r *remoteControl) offButtonWasPushed(slot int) {<br>   fmt.Println(&quot;*****&quot;)<br>   r.offCommands[slot].execute()<br>   fmt.Println(&quot;*****&quot;)<br>}<br><br><strong><em>/**<br> * Implementing String() to print out each slot and its<br> * corresponding command.<br> */</em></strong><br>func (r *remoteControl) String() string {<br>   s := fmt.Sprintf(&quot;\n------ Remote Control -------\n&quot;)<br><br>   for i := range r.onCommands {<br>      if r.onCommands[i] == nil {<br>         continue<br>      }<br><br>      onClass := r.getClassName(r.onCommands[i])<br>      offClass := r.getClassName(r.offCommands[i])<br>      s += fmt.Sprintf(&quot;[slot %d] %s   %s\n&quot;, i, onClass, offClass)<br>   }<br>   s += fmt.Sprintf(&quot;-----------------------------\n&quot;)<br><br>   return s<br>}<br><br>func (r *remoteControl) getClassName(myVar interface{}) string {<br>   if t := reflect.TypeOf(myVar); t.Kind() == reflect.<em>Ptr </em>{<br>      return t.Elem().Name()<br>   } else {<br>      return t.Name()<br>   }<br>}</pre><ul><li>Implementing few Commands</li></ul><pre><strong><em>/**<br> * The LightOffCommand works exactly<br> * the same way as the LightOnCommand,<br> * except that we are binding the receiver<br> * to a different action: the off() method.<br> */</em></strong><br>type lightOffCommand struct {<br>   light *light<br>}<br><br>func newLightOffCommand(l *light) *lightOffCommand {<br>   return &amp;lightOffCommand{<br>      light: l,<br>   }<br>}<br><br>func (l *lightOffCommand) execute() {<br>   l.light.off()<br>}</pre><pre><strong><em>/**<br> * Just like the LightOnCommand, we get<br> * passed the instance of the stereo we<br> * are going to be controlling and we store<br> * it in a local instance variable.<br> */</em></strong><br>type stereoOnCommand struct {<br>   stereo *stereo<br>}<br><br>func newStereoOnCommand(s *stereo) *stereoOnCommand {<br>   return &amp;stereoOnCommand{<br>      stereo: s,<br>   }<br>}<br><br><strong><em>/**<br> * To carry out this request, we need to call three<br> * methods on the stereo: first, turn it on, then set<br> * it to play the CD, and finally set the volume to 11.<br> */</em></strong><br>func (s *stereoOnCommand) execute() {<br>   s.stereo.on()<br>   s.stereo.setCD()<br>   s.stereo.setVolume(11)<br>}</pre><ul><li>Putting the Remote Control to test</li></ul><pre>func main() {<br>   remoteControl := newRemoteControl()<br><br>   <strong><em>// Instantiate all the devices</em></strong><br>   livingRoomLight := &amp;light{&quot;Living Room&quot;}<br>   kitchenLight := &amp;light{&quot;Kitchen&quot;}<br>   ceilingFan := &amp;ceilingFan{&quot;Living Room&quot;}<br>   garage := &amp;garage{}<br>   stereo := &amp;stereo{&quot;Living Room&quot;}<br><br>   <strong><em>// Instantiate all the Command Objects</em></strong><br>   livingRoomLightOn := newLightOnCommand(livingRoomLight)<br>   livingRoomLightOff := newLightOffCommand(livingRoomLight)</pre><pre>   kitchenLightOn := newLightOnCommand(kitchenLight)<br>   kitchenLightOff := newLightOffCommand(kitchenLight)<br><br>   ceilingFanOn := newCeilingFanOnCommand(ceilingFan)<br>   ceilingFanOff := newCeilingFanOffCommand(ceilingFan)<br><br>   stereoOnWithCD := newStereoOnCommand(stereo)<br>   stereoOff := newStereoOffCommand(stereo)<br><br>   garageDoorOpen := newGarageDoorOpenCommand(garage)<br>   garageDoorClose := newGarageDoorCloseCommand(garage)<br><br>   <strong><em>// Load commands into the remote slots</em></strong><br>   remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff)<br>   remoteControl.setCommand(1, kitchenLightOn, kitchenLightOff)<br>   remoteControl.setCommand(2, ceilingFanOn, ceilingFanOff)<br>   remoteControl.setCommand(3, stereoOnWithCD, stereoOff)<br>   remoteControl.setCommand(4, garageDoorOpen, garageDoorClose)<br><br>   fmt.Println(remoteControl)<br><br><strong><em>   //  We step through each slot and push its On and Off button.<br></em></strong>   remoteControl.onButtonWasPushed(0)<br>   remoteControl.offButtonWasPushed(0)<br>   remoteControl.onButtonWasPushed(1)<br>   remoteControl.offButtonWasPushed(1)<br>   remoteControl.onButtonWasPushed(2)<br>   remoteControl.offButtonWasPushed(2)<br>   remoteControl.onButtonWasPushed(3)<br>   remoteControl.offButtonWasPushed(3)<br>   remoteControl.onButtonWasPushed(4)<br>   remoteControl.offButtonWasPushed(4)<br><br>}</pre><ul><li>Run the code!</li></ul><pre>------ Remote Control -------<br>[slot 0] lightOnCommand   lightOffCommand<br>[slot 1] lightOnCommand   lightOffCommand<br>[slot 2] ceilingFanOnCommand   ceilingFanOffCommand<br>[slot 3] stereoOnCommand   stereoOffCommand<br>[slot 4] garageDoorOpenCommand   garageDoorCloseCommand<br>-----------------------------</pre><pre>*****<br>Living Room light is turned on<br>*****<br>*****<br>Living Room light is turned off<br>*****<br>*****<br>Kitchen light is turned on<br>*****<br>*****<br>Kitchen light is turned off<br>*****<br>*****<br>Living Room ceiling fan is turned on<br>*****<br>*****<br>Living Room ceiling fan is turned off<br>*****<br>*****<br>Living Room stereo is on<br>Living Room stereo is set for CD input<br>Living Room stereo volume set to 11<br>*****<br>*****<br>Living Room stereo is off<br>*****<br>*****<br>The Garage is open<br>The Garage Lights are on<br>*****<br>*****<br>The Garage Lights are off<br>The Garage is down<br>*****</pre><h4>Problem Statement 4:</h4><ul><li>Implementing a combo : What if I want to push one button to turn the living room lights and ceiling fan on and the stereo fired up? Let’s call this LivingRoomOnCombo</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>We could implement a LivingRoomOnComboCommand and put the devices to execute their corresponding methods in the LivingRoomOnComboCommand’s execute() method.</li><li>Bu with this, we are essentially “hardcoding” the combo mode.</li><li>Let’s make a MacroCommand, wherein we can decide dynamically which Commands we want to go into the LivingRoomOnComboCommand/LivingRoomOffComboCommand.</li><li>To illustrate, make a new kind of Command that takes an array of commands and execute them.</li></ul><pre>type macroCommand struct {<br>   commands []iCommand<br>}<br><br>func newMacroCommand(c []iCommand) *macroCommand {<br>   return &amp;macroCommand{<br>      commands: c,<br>   }<br>}</pre><pre>func (m * macroCommand) addCommand(c iCommand) {<br>   m.commands = append(m.commands, c)<br>}</pre><pre>func (m *macroCommand) execute() {<br>   for _, command := range m.commands {<br>      command.execute()<br>   }<br>}</pre><ul><li>We create two arrays, one for the On commands and one for the Off commands, and load them with the corresponding commands:</li></ul><pre>livingRoomOnCommands := []iCommand{livingRoomLightOn, ceilingFanOn, stereoOnWithCD}<br>livingRoomOffCommands := []iCommand{livingRoomLightOff, ceilingFanOff, stereoOff}<br>livingRoomMacroOnCommand := newMacroCommand(livingRoomOnCommands)<br>livingRoomMacroOffCommand := newMacroCommand(livingRoomOffCommands)</pre><ul><li>Then we assign MacroCommand to a slot:</li></ul><pre>remoteControl.setCommand(5, livingRoomMacroOnCommand, livingRoomMacroOffCommand)</pre><pre>fmt.Println(&quot;---Pushing Macro On---&quot;)<br>remoteControl.onButtonWasPushed(5)<br><br>fmt.Println(&quot;---Pushing Macro Off---&quot;)<br>remoteControl.offButtonWasPushed(5)</pre><ul><li>Run the Code!</li></ul><pre>---Pushing Macro On---<br>*****<br>Living Room light is turned on<br>Living Room ceiling fan is turned on<br>Living Room stereo is on<br>Living Room stereo is set for CD input<br>Living Room stereo volume set to 11<br>*****<br>---Pushing Macro Off---<br>*****<br>Living Room light is turned off<br>Living Room ceiling fan is turned off<br>Living Room stereo is off<br>*****</pre><h4>BIG PICTURE</h4><ul><li><strong>Use the Command pattern when you want to execute queue operations, schedule their execution, or execute them remotely.</strong></li></ul><p>Imagine a job queue: you add commands to the queue on one end, and on the other end sit a group of threads. Threads run the following script: they remove a command from the queue, call its execute() method, wait for the call to finish, then discard the command object and retrieve a new one.</p><ul><li><strong>Use the Command pattern when you want to parameterise objects with operations and you don’t have a common interface.</strong></li></ul><p>The Command pattern can turn a specific method call into a stand-alone object. This change opens up a lot of interesting uses: you can pass commands as method arguments, store them inside other objects, switch linked commands at runtime, etc.</p><p><em>Next : </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a"><em>Being Adaptive: the Adapter and Facade Patterns</em></a></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8c0a79d1c7" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Head First Design Patterns using Go — 5. Encapsulating Invocation: the Command Pattern</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 4. Baking with OO goodness: the Factory Pattern]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/181bbbf4a8fb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Sun, 09 May 2021 18:41:29 GMT</pubDate>
            <atom:updated>2023-07-26T13:08:24.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 5. Baking with OO goodness: the Factory Pattern</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2HOzv7QeKr7VOLyo" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><strong>Baking with OO goodness: the Factory Pattern</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4>Problem Statement 1:</h4><ul><li>Welcome to the<strong> Pizza shop.</strong></li><li>We want to make pizza by determining the type of the pizza ordered.</li></ul><h4><strong><em>Solution:</em></strong></h4><pre>type Pizza interface {<br> Prepare()<br> Bake()<br> Cut()<br> Box()<br>}<br><br>type CheesePizza struct{}<br><br>func (p *CheesePizza) Prepare() {<br> fmt.Println(&quot;Preparing Cheese Pizza&quot;)<br>}<br><br>func (p *CheesePizza) Bake() {<br> fmt.Println(&quot;Baking Cheese Pizza&quot;)<br>}<br><br>func (p *CheesePizza) Cut() {<br> fmt.Println(&quot;Cutting Cheese Pizza&quot;)<br>}<br><br>func (p *CheesePizza) Box() {<br> fmt.Println(&quot;Boxing Cheese Pizza&quot;)<br>}<br><br>/**<br>* Same goes the implementation for GreekPizza and PepperoniPizza <br>*/<br><br>// PizzaStore object<br>type PizzaStore struct {}<br><br><br>// We pass the type of pizza to orderPizza<br>func (ps *PizzaStore) OrderPizza(pizzaType string) Pizza {<br> var pizza Pizza<br><br> /**<br> * Based on the type of pizza,<br> * we instantiate the correct concrete class<br> * and assign it to the pizza instance variable.<br> * Note that each pizza instance here has to implement the Pizza interface<br> */<br> if pizzaType == &quot;cheese&quot; {<br>  pizza = &amp;CheesePizza{}<br> } else if pizzaType == &quot;greek&quot; {<br>  pizza = &amp;GreekPizza{}<br> } else if pizzaType == &quot;pepperoni&quot; {<br>  pizza = &amp;PepperoniPizza{}<br> }<br><br> /**<br> * Once we have a Pizza, we prepare it!<br> * Each Pizza subtype (CheesePizza, GreekPizza, etc.) <br> * knows how to prepare itself.<br> */<br> pizza.Prepare()<br> pizza.Bake()<br> pizza.Cut()<br> pizza.Box()<br><br> return pizza<br>}</pre><h4>Problem Statement 2:</h4><ul><li>The “OrderPizza” code is <strong>NOT closed for modification</strong>. If the Pizza Shop changes its pizza offerings (add or remove any new pizza), we have to get into the “orderPizza” code and modify it over and over.</li><li>We don’t expect the preparation process (prepare, bake, cut, box etc) to change. So we don’t expect that code to change, just the pizza it operates on.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>Now we know what is varying and what isn’t, it’s time to encapsulate the object creation.</li><li>We take the pizza creation code and move it out of the orderPizza method into another object method that is <strong>only</strong> going to be concerned with creating pizzas.</li><li>We are going to call it a <strong>Factory.</strong></li><li>Factories handle the details of object creation. Once we have a <strong>SimplePizzaFactory</strong>, our “OrderPizza” method just becomes a client of that object. Any time it needs a pizza it asks the pizza factory to make one.</li></ul><pre>/**<br>* Here’s our new struct, the SimplePizzaFactory. <br>* It has one job in life: creating pizzas for its clients.<br>*/ <br>type SimplePizzaFactory struct{}<br><br>func (spf *SimplePizzaFactory) CreatePizza(pizzaType string) Pizza {<br>  var pizza Pizza<br>  switch pizzaType {<br>  case &quot;cheese&quot;:<br>   pizza = &amp;CheesePizza{}<br>  case &quot;pepperoni&quot;:<br>   pizza = &amp;PepperoniPizza{}<br>  case &quot;clam&quot;:<br>   pizza = &amp;ClamPizza{}<br>  case &quot;veggie&quot;:<br>   pizza = &amp;VeggiePizza{}<br>  default:<br>   pizza = nil<br>  }<br><br>  return pizza<br>}</pre><ul><li><strong>Advantage: </strong>By utilizing the SimplePizzaFactory, we <strong>centralize</strong> the pizza creation process and provide a single point of modification when implementing changes.</li><li>SimplePizzaFactory may have many clients other than orderPizza(), such as PizzaShopMenu that uses the factory to get pizzas<br>for their current description and price.</li><li>Moreover, this approach eliminates the need for concrete instantiations in client code, promoting flexibility and maintainability.</li><li>Reworking the PizzaStore client code.</li></ul><pre>type PizzaStore struct {<br> factory SimplePizzaFactory<br>}<br><br>// PizzaStore now has a reference to SimplePizzaFactory<br>func NewPizzaStore(factory SimplePizzaFactory) *PizzaStore {<br> return &amp;PizzaStore{<br>  factory: factory,<br> }<br>}<br><br>func (ps *PizzaStore) OrderPizza(pizzaType string) Pizza {<br> // We pass the type to the factory. <br> // No more concrete instantiations here<br> pizza := ps.factory.CreatePizza(pizzaType)<br> pizza.Prepare()<br> pizza.Bake()<br> pizza.Cut()<br> pizza.Box()<br> return pizza<br>}</pre><ul><li>Looking at the class diagram to understand it better</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*snKjtc9BvaJCgY1Ioi88mw.png" /></figure><h4>Problem Statement 3:</h4><ul><li>The Pizza Store is a success. We want to franchise it now to New York, Chicago and California.</li><li>Now each franchise wants to offer different styles of pizzas, depending on the tastes of the local pizza connoisseurs.</li><li>Ex, NY style pizza has thin crust, tasty sauce and just a little cheese. While, Chicago style pizza has thick crust, rich sauce and tons of cheese.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>Extend SimplePizzaFactory to 3 different factories : NYPizzaFactory, ChicagoPizzaFactory and CaliforniaPizzaFactory.</li><li>Compose the PizzaStore with the appropriate factory and a franchise is good to go.</li><li>Let’s see how the code looks:</li></ul><p>The Pizza Factory</p><pre>type SimplePizzaFactory interface {<br>  CreatePizza(pizzaType string) Pizza<br>}<br><br>type NYPizzaFactory struct {}<br><br>func (ny *NYPizzaFactory) CreatePizza(pizzaType string) Pizza {<br>  // Code to get NY-style pizza<br><br>  return pizza<br>}<br><br>type ChicagoPizzaFactory struct {}<br><br>func (cg *ChicagoPizzaFactory) CreatePizza(pizzaType string) Pizza {<br>  // Code to get Chicago-style pizza<br><br>  return pizza<br>}</pre><p>The Pizza Franchise</p><pre>func main() {<br>  nyFactory := &amp;NYPizzaFactory{}<br>  nyStore := NewPizzaStore(nyFactory)<br>  nyStore.OrderPizza(&quot;Veggie&quot;);<br><br>  chicagoFactory := &amp;ChicagoPizzaFactory{}<br>  chicagoStore := NewPizzaStore(chicagoFactory)<br>  chicagoStore.OrderPizza(&quot;Veggie&quot;);<br>}</pre><ul><li><strong>The Simple Factory isn’t actually a Design Pattern, it’s more of a programming idiom. </strong>It’s a common misconception of equating this with the <strong>Factory Pattern. </strong>The actual Factory Pattern follows next.</li></ul><h4>Problem Statement 4:</h4><ul><li>We decoupled the Pizza factory, but we forgot to decouple the product creation (pizza making).</li><li>There can be local procedures used to make pizza : some would bake things differently, some would not cut the pizza, some would use third-party boxes etc.</li><li>We need to tie the store and pizza creation together, yet allowing things to remain flexible.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>What we’re going to do is put the <strong>createPizza() method </strong>back into PizzaStore, but this time as an <strong>abstract method.</strong></li><li>In Go, there is no direct equivalent of an abstract class like in some other object-oriented languages. However, we can achieve similar behaviour by using interfaces and embedding structs.</li><li>Let’s look how our abstract PizzaStore looks like now</li></ul><pre>type PizzaStore interface {<br>   OrderPizza(pizzaType string) Pizza<br>   CreatePizza(pizzaType string) Pizza<br>}<br><br>// Abstract Pizza Store<br>type BasePizzaStore struct {}<br><br>func (b *BasePizzaStore) OrderPizza(pizzaType string) Pizza {<br>  pizza := b.CreatePizza(pizzaType)<br>  if pizza != nil {<br>   pizza.prepare(); <br>   pizza.bake(); <br>   pizza.cut(); <br>   pizza.box();<br>  }<br>  return pizza;<br>}<br><br>// CreatePizza creates a pizza based on the given type<br>func (b *BasePizzaStore) CreatePizza(pizzaType string) Pizza {<br> // Implement the logic to create a pizza of the given type<br> // and return the corresponding Pizza object.<br> // This method should be implemented by the concrete pizza store classes.<br> // This also prevents accidently initializing BasePizzaStore instance.<br> return nil<br>}</pre><ul><li>Now we are going to subclass for each regional type and each subclass is going to make the decision about what makes up a pizza.</li></ul><pre>type NYStylePizzaStore struct {<br>   BasePizzaStore<br>}<br><br>func (ny *NYStylePizzaStore) createPizza(pizzaType string) Pizza {<br>   switch pizzaType {<br>   case &quot;cheese&quot;:<br>      return &amp;NYStyleCheesePizza{}<br>   case &quot;greek&quot;:<br>      return &amp;NYStyleGreekPizza{}<br>   case &quot;pepperoni&quot;:<br>      return &amp;NYStylePepperoniPizza{}<br>   }<br><br>   return nil<br>}</pre><pre>type ChicagoStylePizzaStore struct {<br>   BasePizzaStore<br>}<br><br>func (c *ChicagoStylePizzaStore) createPizza(pizzaType string) Pizza {<br>   switch pizzaType {<br>   case &quot;cheese&quot;:<br>      return &amp;ChicagoStyleCheesePizza{}<br>   case &quot;greek&quot;:<br>      return &amp;ChicagoStyleGreekPizza{}<br>   case &quot;pepperoni&quot;:<br>      return &amp;ChicagoStylePepperoniPizza{}<br>   }<br><br>   return nil<br>}</pre><ul><li>orderPizza() is defined in the abstract PizzaStore (<strong>BasePizzaStore</strong>), not the subclasses. So the method has no idea which subclass is actually running the code and making the pizzas. In other words, it’s <strong>decoupled.</strong></li><li>All the responsibility for instantiating Pizzas has been moved into a method <strong>createPizza() that acts as factory. </strong>A factory method handles object creation and encapsulates it in a subclass. This decouple the client code in the superclass from the object creation code in the subclass.</li><li>When <strong>orderPizza</strong>() calls <strong>createPizza</strong>(), one of our subclasses will be called into action to create a pizza.</li><li>Which kind of pizza will be made? Well, that’s decided by the choice of pizza store you order from, NYStylePizzaStore or ChicagoStylePizzaStore.</li><li>We are missing an important item here: <strong>PIZZA. </strong>Let’s implement them:</li></ul><p>a. The Abstract Pizza class</p><pre>// Pizza represents the interface class for pizzas<br>type Pizza interface {<br> Prepare()<br> Bake() <br> Cut() <br> Box()<br> GetName() string<br>}<br><br>// BasePizza is the base class for all pizza implementation<br>type BasePizza struct {<br> Name     string<br> Dough    string<br> Sauce    string<br> Toppings []string<br>}<br><br>// Prepare prepares the pizza<br>func (p *BasePizza) Prepare() {<br> fmt.Printf(&quot;Preparing %s\n&quot;, p.Name)<br> fmt.Println(&quot;Tossing dough...&quot;)<br> fmt.Println(&quot;Adding sauce...&quot;)<br> fmt.Println(&quot;Adding toppings:&quot;)<br> for _, topping := range p.Toppings {<br>  fmt.Printf(&quot; %s\n&quot;, topping)<br> }<br>}<br><br>// Bake bakes the pizza<br>func (p *BasePizza) Bake() {<br> fmt.Println(&quot;Bake for 25 minutes at 350&quot;)<br>}<br><br>// Cut cuts the pizza<br>func (p *BasePizza) Cut() {<br> fmt.Println(&quot;Cutting the pizza into diagonal slices&quot;)<br>}<br><br>// Box boxes the pizza<br>func (p *BasePizza) Box() {<br> fmt.Println(&quot;Place pizza in official PizzaStore box&quot;)<br>}<br><br>// GetName returns the name of the pizza<br>func (p *BasePizza) GetName() string {<br> return p.Name<br>}</pre><p>b. Implementing some concrete subclasses</p><pre>// NYStyleCheesePizza represents a New York style cheese pizza<br>type NYStyleCheesePizza struct {<br> BasePizza<br>}<br><br>func NewNYStyleCheesePizza() Pizza {<br>   pizza: BasePizza{<br>    Name:     &quot;NY Style Sauce and Cheese Pizza&quot;,<br>    Dough:    &quot;Thin Crust Dough&quot;,<br>    Sauce:    &quot;Marinara Sauce&quot;,<br>    Toppings: []string{&quot;Grated Reggiano Cheese&quot;},<br>   },<br><br>   return &amp;NYStyleCheesePizza{<br>      BasePizza: pizza,<br>   }<br>}<br><br>// ChicagoStyleCheesePizza represents a Chicago style cheese pizza<br>type ChicagoStyleCheesePizza struct {<br> BasePizza<br>}<br><br>// Cut overrides the Cut method for Chicago style pizza<br>func (c *ChicagoStyleCheesePizza) Cut() {<br> fmt.Println(&quot;Cutting the pizza into square slices&quot;)<br>}<br><br>func NewChicagoStyleCheesePizza() Pizza {<br>   pizza: BasePizza{<br>    Name:     &quot;Chicago Style Deep Dish Cheese Pizza&quot;,<br>    Dough:    &quot;Extra Thick Crust Dough&quot;,<br>    Sauce:    &quot;Plum Tomato Sauce&quot;,<br>    Toppings: []string{&quot;Shredded Mozzarella Cheese&quot;},<br>   },<br><br>   return &amp;ChicagoStyleCheesePizza{<br>      BasePizza: pizza,<br>   }<br>}</pre><ul><li>Let’s order some pizzas for two customers, say : Ethan and Joel</li></ul><pre>func main() {<br> nyPizzaStore := &amp;NYStylePizzaStore{}<br> pizza := nyPizzaStore.OrderPizza(&quot;cheese&quot;)<br> fmt.Printf(&quot;Ethan ordered a %s\n\n&quot;, pizza.GetName())<br><br> chicagoPizzaStore := &amp;ChicagoStylePizzaStore{}<br> pizza = chicagoPizzaStore.OrderPizza(&quot;cheese&quot;)<br> fmt.Printf(&quot;Joel ordered a %s\n\n&quot;, pizza.GetName())<br>}</pre><ul><li>Run the code!</li></ul><pre>Preparing NY Style Sauce and Cheese Pizza Pizza<br>Tossing Thin Crust Dough dough<br>Adding Marinara Sauce sauce<br>Adding toppings: <br>        Grated Reggiano Cheese, <br>Baking Pizza for 25 min at 350<br>Cutting the pizza into diagonal slices<br>Place pizza in official PizzaStore box<br>Ethan ordered NY Style Sauce and Cheese Pizza pizza</pre><pre>Preparing Chicago Style Deep Dish Cheese Pizza Pizza<br>Tossing Extra Thick Crust Dough dough<br>Adding Plum Tomato Sauce sauce<br>Adding toppings: <br>        Shredded Mozzarella Cheese, <br>Baking Pizza for 25 min at 350<br>Cutting the pizza into square slices<br>Place pizza in official PizzaStore box<br>Joel ordered Chicago Style Deep Dish Cheese Pizza pizza</pre><ul><li>Meet <strong>Factory Design Pattern.</strong></li><li>Wiki Definition: The <strong>Factory Pattern</strong> defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.</li><li>Let’s understand this using the following class diagram:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGGYuNCofN083y9jsRd25Q.png" /><figcaption>Final UML Diagram</figcaption></figure><h4>Problem Statement 5:</h4><ul><li>How is <strong>Factory Pattern</strong> different from the <strong>Simple Factory</strong> method?</li></ul><p><strong><em>Solution:</em></strong></p><ul><li>Even though the implementation of the concrete stores look a lot like the SimplePizzaFactory, the concrete stores are extending a class which has defined the createPizza() as an abstract method.</li><li>It is upto each store to define the behaviour of the createPizza() method. In SimpleFactory, the factory is another object that is composed with the PizzaStore.</li><li>With the Factory Pattern, we have created a framework that lets the subclasses decide which implementation of createPizza() will be used.</li><li>Comparing it with Simple Factory, which gives you a way to encapsulate object creation, but doesn’t give you the flexibility of varying the creation of the products.</li></ul><h4>BIG PICTURE</h4><ul><li><strong>The Factory Pattern separates product construction code from the code that actually uses the product. Therefore it’s easier to extend the product construction code independently from the rest of the code. Example, to franchise the PizzaStore to new areas, we need to just create a new creator subclass and override the factory method (createPizza) in that.</strong></li><li><strong>Use the Factory Method when you want to reuse the existing objects instead of rebuilding them each time.</strong></li></ul><p><em>Next : </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7"><em>Encapsulating Invocation: the Command Pattern</em></a></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=181bbbf4a8fb" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Head First Design Patterns using Go — 4. Baking with OO goodness: the Factory Pattern</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 3. Decorating Objects: the Decorator Pattern]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c35636722da7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Tue, 04 May 2021 22:54:01 GMT</pubDate>
            <atom:updated>2023-07-03T20:00:22.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 4. Decorating Objects: the Decorator Pattern</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*UDJY4_QCXmEmGvnm.png" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><strong>Decorating Objects: the Decorator Pattern</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4>Problem Statement 1:</h4><ul><li>Welcome to <strong>Starbuzz Coffee</strong>, the newly opened coffee shop in the neighbourhood.</li><li>Currently they have a limited range of offerings — HouseBlend, DarkRoast, Decaf and Espresso.</li><li>Design a system to get the cost of the beverage ordered.</li></ul><h4><strong><em>Solution</em></strong><em>:</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*mIIcSKcDyLZYTXmgYAZFaA.png" /></figure><h4>Problem Statement 2:</h4><ul><li>Now, as they are experiencing rapid growth, they need to update their selection of beverages.</li><li>In addition to coffee, you can also add condiments like steamed milk, soy, mocha (chocolate), and whipped milk to your order at Starbuzz. These extras come at an additional cost, so they are essential to incorporate into the order system.</li><li>Class Explosion, Maintenance Nightmare</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DsxmG4d9CM4jDyCkKSqZg.png" /></figure><h4><strong><em>Solution</em></strong><em>:</em></h4><ul><li>We can use instance variables and inheritance in the superclass to keep track of the condiments. As in, the Beverage base class can have instance variables to represent whether or not each beverage has milk, soy, mocha, whip etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*bElGhA1XcL_ZvdNiDQLYQg.png" /></figure><ul><li>The superclass cost() method calculates the costs of all condiments, while the overridden cost() method in the subclasses extends this functionality to include costs specific to each beverage type.</li><li>Each cost() method computes the beverage’s cost and adds the condiment costs by invoking the superclass implementation of cost().</li></ul><pre>type Beverage struct {<br> milkCost float64<br> soyCost  float64<br> mochaCost float64<br> whipCost float64<br>}<br><br>func (b *Beverage) Cost() float64 {<br> condimentCost := 0.0<br> if b.hasMilk() {<br>  condimentCost += b.milkCost<br> }<br> if b.hasSoy() {<br>  condimentCost += b.soyCost<br> }<br> if b.hasMocha() {<br>  condimentCost += b.mochaCost<br> }<br> if b.hasWhip() {<br>  condimentCost += b.whipCost<br> }<br> return condimentCost<br>}<br><br>// DarkRoast extends Beverage struct<br>type DarkRoast struct {<br> Beverage<br>}<br><br>func (d *DarkRoast) Cost() float64 {<br> return 1.99 + d.Beverage.Cost()<br>}<br><br>func main() {<br> darkRoast := &amp;DarkRoast{}<br> fmt.Println(darkRoast.cost())<br>}</pre><h4>Problem Statement 3:</h4><ul><li>Price changes for condiments will force us to alter existing code.</li><li>New condiments will make us add new methods and alter the cost method in superclass.</li><li>We may have new beverages. For some of these beverages (like iced tea), the condiments may not be appropriate, yet the Tea subclass will still inherit methods like hasWhip().</li><li>What if a customer wants a double mocha?</li></ul><h4><strong><em>Solution</em></strong><em>:</em></h4><ul><li>While inheritance is powerful, it doesn’t always lead to the most flexible or maintainable designs.</li><li>So how can achieve reuse if not through inheritance? — “Inheriting” behaviour at runtime through composition and delegation.</li><li>When the behaviour is inherited by subclassing, that behaviour is set statically at compile time. In addition, all subclasses must inherit the same behaviour.</li><li>If however, an object’s behaviour is extended through composition, then this can be done dynamically at runtime.</li><li>By dynamically composing objects, I can add new functionality by writing new code rather than altering existing code.</li><li>For example in <strong>Observer</strong> pattern, by adding new <em>Observers</em>, we can extend the <em>Subject</em> at any time, without adding code to the Subject.</li><li>This brings us to one of the most important design principles.</li></ul><blockquote><strong>Design Principle 5: Classes should be open for extension, but closed for modification</strong>.</blockquote><ul><li>For our Starbuzz Coffee shop, we will start with a beverage and “decorate” it with the condiments at runtime. For example, if the customer wants a Dark Roast with mocha and whip, then we’ll:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*4j-DWPea4bGA62SOwwk0fw.png" /></figure><ul><li>So how do we “decorate” an object and how does delegation come into this?</li><li>Solution : think of the decorator objects as wrappers. Let’s see how it works….</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*EIlxCWuI0p7J8w7vE87uww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*0VQ2OSP0jzlX--9jTy5Txg.png" /></figure><ul><li>Meet the <strong>DECORATOR</strong> Pattern</li><li>Definition: The <strong>Decorator Pattern</strong> attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality</li><li>Decorators have the same supertype as the objects they decorate.</li><li>You can use one or more decorators to wrap an object.</li><li>The decorator adds its own behaviour either before and/or after delegating to the object it decorates to do the rest of the job.</li><li>Objects can be decorated at any time, so we can decorate objects dynamically at runtime with as many decorators as we like.</li><li>Decorator Pattern defined via the class diagram:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*On1M_IBzj_66mj-hBVcNtg.png" /></figure><ul><li>Let’s work our Starbuzz beverages into this framework.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*bL-1cYR0JTv5E5Gbk3PWXA.png" /></figure><ul><li>But we weren’t going to use Inheritance, were we? The CondimentDecorator extends the Beverage class.</li><li>While inheritance is used to achieve type matching between decorators and components, it is not used to inherit behaviour.</li><li>The behaviour is introduced through composition, where decorators are composed with components and other decorators. This composition allows for the addition of new behaviour dynamically at runtime, providing flexibility in mixing and matching condiments and beverages, without modifying existing code.</li></ul><h4>Show me the code:</h4><ul><li>Start with base interfaces — Beverage and CondimentDecorator</li></ul><pre>// Component<br>type Beverage interface {<br> Cost() float64<br> GetDescription() string<br>}<br><br>// Decorator<br>type CondimentDecorator interface {<br> Beverage<br> // New method added to the CondimentDecorator interface<br> AddOnDescription() string <br>}</pre><ul><li>Coding Beverages</li></ul><pre>// ConcreteComponent<br>type Espresso struct{}<br><br>func NewEspresso() Beverage {<br> return &amp;Espresso{}<br>}<br><br>func (e *Espresso) Cost() float64 {<br> return 1.99<br>}<br><br>func (e *Espresso) GetDescription() string {<br> return &quot;Espresso&quot;<br>}</pre><pre>// ConcreteComponent: DarkRoast<br>type DarkRoast struct{}<br><br>func NewDarkRoast() Beverage {<br> return &amp;DarkRoast{}<br>}<br><br>func (d *DarkRoast) Cost() float64 {<br> return 0.99<br>}<br><br>func (d *DarkRoast) GetDescription() string {<br> return &quot;Dark Roast Coffee&quot;<br>}</pre><ul><li>Coding Condiments</li></ul><pre>// ConcreteDecorator<br>type Milk struct {<br> beverage Beverage<br>}<br><br>func NewMilk(beverage Beverage) Beverage{<br> return &amp;Milk{beverage: beverage}<br>}<br><br>func (m *Milk) Cost() float64 {<br> return 0.1 + m.beverage.Cost()<br>}<br><br>func (m *Milk) GetDescription() string {<br> return m.beverage.GetDescription() + m.AddOnDescription() <br>}<br><br>func (m *Milk) AddOnDescription() string {<br> return &quot;\n +AddOn Milk&quot;<br>}</pre><pre>// ConcreteDecorator<br>type Mocha struct {<br> beverage Beverage<br>}<br><br>func NewMocha(beverage Beverage) Beverage{<br> return &amp;Mocha{beverage: beverage}<br>}<br><br>func (m *Mocha) Cost() float64 {<br> return 0.2 + m.beverage.Cost()<br>}<br><br>func (m *Mocha) GetDescription() string {<br> return m.beverage.GetDescription() + m.AddOnDescription()<br>}<br><br>func (m *Mocha) AddOnDescription() string {<br> return &quot;\n +AddOn Mocha&quot;<br>}</pre><pre>// ConcreteDecorator<br>type Soy struct {<br> beverage Beverage<br>}<br><br>func NewSoy(beverage Beverage) Beverage{<br> return &amp;Soy{beverage: beverage}<br>}<br><br>func (s *Soy) Cost() float64 {<br> return 0.15 + s.beverage.Cost()<br>}<br><br>func (s *Soy) GetDescription() string {<br> return s.beverage.GetDescription() + s.AddOnDescription()<br>}<br><br>func (s *Soy) AddOnDescription() string {<br> return &quot;\n +AddOn Soy&quot;<br>}</pre><ul><li>Serving some coffees</li></ul><pre>func main() {<br> // Order up an espresso, no condiments<br> beverage1 := &amp;Espresso{}<br> fmt.Println(&quot;Order1:&quot;, beverage1.GetDescription())<br> fmt.Println(&quot;Cost:&quot;, beverage1.Cost())<br><br> // Create a DarkRoast coffee with milk and mocha<br> beverage2 := NewMocha(NewMilk(&amp;DarkRoast{}))<br><br> fmt.Println(&quot;Order2:&quot;, beverage2.GetDescription())<br> fmt.Println(&quot;Cost:&quot;, beverage2.Cost())<br><br> // Add a new decorator (Soy) at runtime<br> beverage2 = NewSoy(beverage2)<br><br> fmt.Println(&quot;Updated Order2:&quot;, beverage2.GetDescription())<br> fmt.Println(&quot;Updated Cost:&quot;, beverage2.Cost())<br>}</pre><ul><li>Run the code!</li></ul><pre>Order1: Espresso<br>Cost: 1.99<br>Order2: Dark Roast Coffee<br> +AddOn Milk<br> +AddOn Mocha<br>Cost: 1.29<br>Updated Order2: Dark Roast Coffee<br> +AddOn Milk<br> +AddOn Mocha<br> +AddOn Soy<br>Updated Cost: 1.44</pre><h4>SUMMARY</h4><ul><li><strong>OO Principles</strong></li></ul><blockquote>Design Principle 5: Classes should be open for extension, but closed for modification.</blockquote><ul><li>OO Patterns</li></ul><p>Decorator — Attach additional responsibilities to an object dynamically. Decorators provide a flexible automatically alternative to subclassing for extending functionality.</p><p><em>Next : </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb"><em>Baking with OO goodness: the Factory Pattern</em></a></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c35636722da7" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Head First Design Patterns using Go — 3. Decorating Objects: the Decorator Pattern</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 2. Keeping your Objects in the know: the Observer Pattern]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/948e6b5b66fc</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Mon, 03 May 2021 21:21:51 GMT</pubDate>
            <atom:updated>2023-07-03T20:00:10.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 3. Keeping your Objects in the know: the Observer Pattern</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Q3AM7IdclxaX0ybXMmUtXg.jpeg" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><strong>Keeping your Objects in the know: the Observer Pattern</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4>Problem Statement 1:</h4><ul><li>There is a <strong>WeatherData</strong> object which tracks current weather conditions (temperature, humidity and barometric pressure).</li><li>Develop a <strong>Weather Monitoring Station</strong> that uses this object to provide three display elements : current conditions, weather statistics and a forecast, all updated in real time as as the WeatherData object acquires the most recent measurements.</li></ul><h4><strong><em>Solution</em></strong><em>:</em></h4><ul><li>3 players in the system : <strong>the weather station</strong> (the physical device that acquires the actual weather data), the <strong>WeatherData</strong> object (that tracks the data coming from the Weather Station and updates the displays), and the <strong>display</strong> that shows users the current weather conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dhQKGI2AQtOTQ-S3Jpstw.png" /></figure><h4>Problem Statement 2:</h4><ul><li>Unpacking the WeatherData source file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*X1c1dGEtVDGQM_xnrM6y4g.png" /></figure><pre>/**<br>* This method gets called<br>* whenever the weather measurements<br>* have been updated<br>**/<br>func (wd *WeatherData) measurementsChanged() {<br>  // Your code goes here<br>}</pre><ul><li>We need to implement measurementsChanged() so that it updates the three displays for current conditions, weather stats and forecast.</li><li>System must be expandable — new custom display elements can be created or removed.</li></ul><h4><strong><em>Solution</em></strong><em>:</em></h4><ul><li>Here’s a first possible implementation wherein we are adding code to the measurementsChanged() method.</li></ul><pre>type WeatherData struct {<br>  // Instance variables<br>  temperature float32<br>  humidity    float32<br>  pressure    float32<br>  currentConditionDisplay CurrentConditionDisplay<br>  statisticsDisplay StatisticsDisplay<br>  forecastDisplay ForecastDisplay<br>}<br><br>func (w *WeatherData) measurementsChanged() {<br>  /**<br>  * Grab the most recent measurements<br>  * by calling the WeatherData&#39;s getter methods<br>  **/ <br>  temp := w.GetTemparature()<br>  pressure := w.GetPressure()<br>  humidity := w.GetHumidity()<br><br>  /**<br>  * Now update the displays<br>  * Call each display element to update its display,<br>  * passing it the most recent measurements<br>  **/<br>  w.currentConditionDisplay.Update(temp, humidity, pressure)<br>  w.statisticsDisplay.Update(temp, humidity, pressure)<br>  w.forecastDisplay.Update(temp, humidity, pressure)<br>}</pre><h4>Problem Statement 3:</h4><ul><li>We are coding to concrete implementations, not interfaces.</li><li>For every new display element, we need to alter code.</li><li>We have no way to add (or remove) display elements at runtime.</li><li>We haven’t encapsulated the part that changes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*z-CU49d76SemvDkKtl5HAA.png" /></figure><h4><strong><em>Solution</em></strong><em>:</em></h4><ul><li>Meet the <strong>OBSERVER</strong> Pattern</li><li>Publishers + Subscribers <strong>≈ Observer Pattern</strong></li><li>Analogy with newspaper subscription:</li></ul><blockquote>- A newspaper publisher begins publishing newspapers <strong>≈ </strong>WeatherData starts publishing weather data</blockquote><blockquote>- Once subscribed to a particular newspaper, and every time there’s a new edition it gets delivered to you. As long as you remain a subscriber, you get new newspapers <strong>≈ </strong>The Display elements subscribe to the weather data and process data according to their requirements as long as they are subscribed to the WeatherData</blockquote><blockquote>- You can frequently subscribe or unsubscribe <strong>≈ </strong>new Display elements can be subscribed or unsubscribed to the WeatherData object at runtime.</blockquote><ul><li>Definition: The <strong>Observer Pattern</strong> defines a one-to-many relationship between a set of objects. When the state of one object changes, all of its dependents are notified.</li><li>Observer Pattern defined via the class diagram:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*FFCne4a8hsitr6t5JV02Mw.png" /></figure><ul><li><strong>When two objects are loosely coupled, they can interact, but have very little knowledge of each other. The Observer Pattern provides an object design where subjects and observers are loosely coupled. Why?</strong></li></ul><blockquote><em>- The only thing the subject knows about an observer is that it implements a certain interface (the Observer interface). </em>It doesn’t need to know the concrete class of the observer, what it does, or anything else about it.</blockquote><blockquote><em>- We can add/remove/replace observers at any time. </em>Because the only thing the subject depends on is a list of objects that implement the Observer interface.</blockquote><blockquote><em>- We never need to modify the subject to add new types of observers.</em></blockquote><blockquote><em>- We can reuse subjects or observers independently of each other.</em></blockquote><blockquote><em>- Changes to either the subject or an observer will not affect the other.</em></blockquote><blockquote><strong>Design Principle 4: Strive for loosely coupled designs between objects that interact.</strong></blockquote><ul><li>Let’s see how the class diagram looks like for the Weather Station</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*vl6zSS1Jw-xQWlLCFpv7Vw.png" /></figure><h4>Show me the code:</h4><ul><li>Start with interfaces</li></ul><pre>/**<br>* Observer interface is implemented by all observers,<br>* Here we&#39;re passing the measurements to the observers<br>* from the Subject when a weather measurement changes<br>*/<br>type Observer interface {<br> Update(temp, humidity, pressure float64)<br>}<br><br>// Subject interface<br>type Subject interface {<br> /**<br> * Both of these methods take an Observer as argument<br> * that is, the Observer to be registered or removed.<br> */<br> RegisterObserver(observer Observer)<br> RemoveObserver(observer Observer)<br> /**<br> * This method is called to notify all the observers<br> * when the Subject&#39;s state has changed<br> */<br> NotifyObservers()<br>}<br><br>/**<br> * DisplayElement interface just includes display() method<br> * that we will call when the info needs to be displayed<br> */<br>type DisplayElement interface {<br>   Display()<br>}</pre><ul><li>Implementing the Subject interface in WeatherData</li></ul><pre>// WeatherData struct<br>type WeatherData struct {<br> observers []Observer<br> temperature, humidity, pressure float64<br>}<br><br>// NewWeatherData creates a new WeatherData instance<br>func NewWeatherData() *WeatherData {<br> return &amp;WeatherData{}<br>}<br><br>// RegisterObserver registers an observer<br>func (wd *WeatherData) RegisterObserver(observer Observer) {<br> wd.observers = append(wd.observers, observer)<br>}<br><br>// RemoveObserver removes an observer<br>func (wd *WeatherData) RemoveObserver(observer Observer) {<br> index := -1<br> for i, obs := range wd.observers {<br>  if obs == observer {<br>   index = i<br>   break<br>  }<br> }<br> if index &gt;= 0 {<br>  wd.observers = append(wd.observers[:index], wd.observers[index+1:]...)<br> }<br>}<br><br>// NotifyObservers notifies all observers by calling their update() method<br>func (wd *WeatherData) NotifyObservers() {<br> for _, observer := range wd.observers {<br>  observer.Update(wd.temperature, wd.humidity, wd.pressure)<br> }<br>}<br><br>// We notify the Observers when measurements are updated<br>func (wd *WeatherData) measurementsChanged() {<br> wd.NotifyObservers()<br>}<br><br>// SetMeasurements sets the weather measurements and notifies observers<br>func (wd *WeatherData) SetMeasurements(temperature, humidity, pressure float64) {<br> wd.temperature = temperature<br> wd.humidity = humidity<br> wd.pressure = pressure<br> wd.measurementsChanged()<br>}</pre><ul><li>Now, let’s build those display elements. Each of the display elements will implement the Observer and DisplayElement interfaces.</li></ul><p>CurrentConditionDisplay</p><pre>// CurrentConditionsDisplay struct<br>type CurrentConditionsDisplay struct {<br> temperature, humidity float64<br>}<br><br>// NewCurrentConditionsDisplay creates a new CurrentConditionsDisplay instance<br>func NewCurrentConditionsDisplay() *CurrentConditionsDisplay {<br> return &amp;CurrentConditionsDisplay{}<br>}<br><br>// Update save the measurements and displays the required information<br>func (ccd *CurrentConditionsDisplay) Update(temp, humidity, pressure float64) {<br> ccd.temperature = temp<br> ccd.humidity = humidity<br> ccd.Display()<br>}<br><br>// Display displays the current conditions<br>func (ccd *CurrentConditionsDisplay) Display() {<br> fmt.Printf(&quot;Current conditions: %.2f°F temperature and <br>                %.2f%% humidity\n&quot;, ccd.temperature, ccd.humidity)<br>}</pre><p>StatisticsDisplay</p><pre>// StatisticsDisplay struct<br>type StatisticsDisplay struct {<br> minTemp, maxTemp, avgTemp float64<br> temperatureCount          int<br>}<br><br>// NewStatisticsDisplay creates a new StatisticsDisplay instance<br>func NewStatisticsDisplay() *StatisticsDisplay {<br> return &amp;StatisticsDisplay{}<br>}<br><br>// Update calculates avg, min and max temp and displays the information<br>func (sd *StatisticsDisplay) Update(temp, humidity, pressure float64) {<br> if sd.temperatureCount == 0 {<br>  sd.minTemp = temp<br>  sd.maxTemp = temp<br>  sd.avgTemp = temp<br> } else {<br>  if temp &lt; sd.minTemp {<br>   sd.minTemp = temp<br>  }<br>  if temp &gt; sd.maxTemp {<br>   sd.maxTemp = temp<br>  }<br>  sd.avgTemp = (sd.avgTemp*float64(sd.temperatureCount) + temp) / float64(sd.temperatureCount+1)<br> }<br><br> sd.temperatureCount++<br> sd.Display()<br>}<br><br>// Display displays the statistics<br>func (sd *StatisticsDisplay) Display() {<br> fmt.Printf(&quot;Temperature statistics: Min %.2f°F, Max %.2f°F, <br>              Average %.2f°F\n&quot;, sd.minTemp, sd.maxTemp, sd.avgTemp)<br>}</pre><ul><li>Let’s Power Up the Weather Station Now</li></ul><pre>func main() {<br> weatherData := NewWeatherData()<br><br> currentConditionsDisplay := NewCurrentConditionsDisplay()<br> statisticsDisplay := NewStatisticsDisplay()<br><br> weatherData.RegisterObserver(currentConditionsDisplay)<br> weatherData.RegisterObserver(statisticsDisplay)<br><br> weatherData.SetMeasurements(80, 65, 30.4)<br> weatherData.SetMeasurements(82, 70, 29.2)<br> weatherData.SetMeasurements(78, 90, 29.2)<br>}</pre><ul><li>Run the code!</li></ul><pre>Current conditions: 80.00°F temperature and 65.00% humidity<br>Temperature statistics: Min 80.00°F, Max 80.00°F, Average 80.00°F<br>Current conditions: 82.00°F temperature and 70.00% humidity<br>Temperature statistics: Min 80.00°F, Max 82.00°F, Average 81.00°F<br>Current conditions: 78.00°F temperature and 90.00% humidity<br>Temperature statistics: Min 78.00°F, Max 82.00°F, Average 80.00°F</pre><h4>Design Principles Recap</h4><p>Let’s see if Observer pattern makes use of the OO design principles defined in the previous article.</p><blockquote><strong>Design Principle 1: Identify the aspects of your application that vary and separate them from what stays the same.</strong></blockquote><blockquote>In the Observer Pattern, the varying aspects are the state of the Subject and the number and types of Observers. With this pattern, you can change the objects dependent on the state of the Subject without modifying the Subject itself.</blockquote><blockquote><strong>Design Principle 2: Program to an interface, not an implementation.</strong></blockquote><blockquote>Both the Subject and Observer use interfaces. The Subject keeps track of objects implementing the Observer interface, while the observers register with, and get notified by, the Subject interface. As we’ve seen, this keeps things nice and loosely coupled.</blockquote><blockquote><strong>Design Principle 3: Favour composition (HAS-A relationship) over inheritance (IS-A relationship)</strong></blockquote><blockquote>The Observer Pattern uses composition to compose any number of Observers with their Subjects. These relationships aren’t set up by some kind of inheritance hierarchy. They are set up at runtime by composition!</blockquote><h4>SUMMARY</h4><ul><li><strong>OO Principles</strong></li></ul><blockquote>Design Principle 4: Strive for loosely coupled designs between objects that interact.</blockquote><ul><li><strong>OO Patterns</strong></li></ul><p>Observer — defines a one-to-many dependency between objects so that when the state of one object changes, all of its dependents are notified and updated automatically.</p><p><em>Next : </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7"><em>Decorating Objects: the Decorator Pattern</em></a></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948e6b5b66fc" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Head First Design Patterns using Go — 2. Keeping your Objects in the know: the Observer Pattern</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — 1. Welcome to Design Patterns: the Strategy Pattern]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cbd940e113a</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Mon, 03 May 2021 21:20:10 GMT</pubDate>
            <atom:updated>2023-07-03T09:29:33.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go — 2. Welcome to Design Patterns: the Strategy Pattern</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*X0OFZFuS4IbWVvAz.png" /></figure><p><strong>Table of Contents</strong></p><ol><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Introduction</a></li><li><strong>Welcome to Design Patterns: the Strategy Pattern</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><h4><strong>Problem Statement 1:</strong></h4><ul><li>Develop a game, <strong>SimUDuck app </strong>which<strong> </strong>shows a large variety of duck species swimming and making quacking sounds.</li></ul><h4><strong>Solution:</strong></h4><ul><li>Standard OO techniques and created one Duck superclass from which all other duck types inherit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*Y-f67i9FfsbF5B8mcTgwww.png" /></figure><h4>Problem Statement 2:</h4><ul><li>Now we need ducks to <strong>FLY.</strong></li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>Add a fly() method in the Duck class and then all the ducks will inherit it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*hyIXo21cKO-LQA23-rwvig.png" /></figure><h4>Problem Statement 3:</h4><ul><li><strong>Rubber Duckies</strong> are flying around the screen.</li><li>Not all <strong>subclasses</strong> of Duck have <em>the </em><strong>flying behaviour</strong>.</li><li>Neither do all <strong>quack.</strong></li><li>What was thought as a great use of <strong>inheritance</strong> for the purpose of <strong>reuse</strong> hasn’t turned out so well when it comes to <strong>maintenance</strong>.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>Override the fly() and quack() methods in the RubberDuck class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*6npGRRPd95M5JbnOq6BQ6w.png" /></figure><h4>Problem Statement 4:</h4><ul><li>What happens when we add wooden decoy ducks? They neither fly nor quack.</li><li>Code is duplicated across subclasses.</li><li>Runtime behaviour changes are difficult.</li><li>Hard to gain knowledge of all duck behaviours.</li><li>Changes can unintentionally affect other ducks.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>Bring in <strong>Interface </strong>: take the fly() out of the Duck superclass make a <strong>Flyable() interface with a fly() method.</strong></li><li>That way, only the ducks that are supposed to fly will implement that interface and have a fly() method</li><li>Same goes for<strong> quack()</strong> behaviour</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*3z_YPDuXREUWqJoMVk214w.png" /></figure><h4>Problem Statement 5:</h4><ul><li>Code is duplicated across subclasses — maintenance nightmare.</li><li>Any change in flying behaviour needs to implemented across all flying Duck subclasses.</li><li>There can be more than one kind of flying behaviour even among the ducks that do fly.</li></ul><h4><strong><em>Solution:</em></strong></h4><ul><li>The one constant in software development — CHANGE. No matter how well you design an application, over time an application must grow and change or it will die.</li></ul><blockquote><strong>Design Principle 1: Identify the aspects of your application that vary and separate them from what stays the same.</strong></blockquote><ul><li>Take what varies and “<strong>encapsulate</strong>” it so it won’t affect the rest of your code.</li><li>Result? Fewer unintended consequences from code changes and more flexibility in your systems</li><li>Looking at the Duck class, other than problems with fly() and quack(), it is working well and there are no other parts that appear to vary or change frequently.</li><li>To separate the “parts that change from those that stay the same”, we’ll pull both methods out of the Duck class and create a new set of classes to represent each behaviour. For instance, we might have one class that implements <strong>quacking</strong>, another that implements <strong>squeaking</strong>, and another that implements <strong>silence</strong></li></ul><h4>Problem Statement 6:</h4><ul><li>So how are we going to design the set of classes that implement the fly and quack behaviours?</li></ul><h4>Solution:</h4><blockquote><strong>Design Principle 2: Program to an interface, not an implementation.</strong></blockquote><ul><li>The point is to exploit polymorphism by programming to a supertype so that the actual runtime object isn’t locked into the code.</li><li>Here’s a simple example of using a polymorphic type — imagine an abstract class Animal, with two concrete implementations, Dog and Cat.</li><li><strong>Programming to an implementation</strong> would be:</li></ul><pre>// Declaring the variable &quot;d&quot; as type Dog <br>// (a concrete implementation of Animal)<br>// forces us to code to a concrete implementation<br>type Animal interface {<br> MakeSound()<br>}<br><br>type Dog struct{}<br><br>func (d Dog) MakeSound() {<br> fmt.Println(&quot;Woof!&quot;)<br>}<br><br>func main() {<br> var d Dog = Dog{}<br> d.MakeSound()<br>}</pre><ul><li>But<strong> programming to an interface/supertype</strong> would be:</li></ul><pre>// We know it&#39;s a Dog, <br>// but we can use the animal<br>// reference polymorphically.<br>type Animal interface {<br> MakeSound()<br>}<br><br>type Dog struct{}<br><br>func (d Dog) MakeSound() {<br> fmt.Println(&quot;Woof!&quot;)<br>}<br><br>func main() {<br> var animal Animal = Dog{}<br> animal.MakeSound()<br>}</pre><ul><li>The key is that a Duck will now delegate its flying and quacking behaviour, instead of using fly() and quack() methods defined in the Duck class (or subclasses).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*e8rC6NwQEgPBVacpN6RC8Q.png" /></figure><ul><li>The Duck subclasses utilize interfaces (FlyBehaviour and QuackBehaviour) to represent their behaviours. This ensures that the specific implementation of each behaviour, coded in classes that implement the corresponding interfaces, can be easily changed without impacting the Duck subclasses.</li><li>That way, the Duck classes won’t need to know any of the implementation details for their own behaviours.</li><li>Benefits of this design : a) code reusability, b) new behaviours can be added without modifying any of our existing behaviour classes or touching any of the Duck classes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPeMPQhwWbeIq3kg59b5HQ.png" /></figure><ul><li>Pay careful attention to the relationships between the classes (IS-A, HAS-A and IMPLEMENTS).</li><li>The HAS-A relationship is an interesting one: each duck has a FlyBehaviour and a QuackBehaviour to which it delegates flying and quacking.</li><li>When you put two classes together like this you’re using <strong>composition</strong>. Instead of inheriting their behaviour, the ducks get their behaviour by being composed with the right behaviour object.</li></ul><blockquote><strong>Design Principle 3: Favour composition (HAS-A relationship) over inheritance (IS-A relationship)</strong></blockquote><ul><li>Lets you encapsulate a family of algorithms into their own set of classes,</li><li>Gives more flexibility, can change behaviour/algorithm at runtime</li><li>Congratulations on learning the first design pattern : the <strong>STRATEGY</strong> pattern</li><li>Definition: The<strong> Strategy Pattern</strong> defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</li></ul><h4>Show me the code:</h4><ul><li>FlyBehaviour set of classes</li></ul><pre>// FlyBehaviour interface that all flying behaviour classes implement<br>type FlyBehaviour interface {<br> Fly()<br>}<br><br>// Flying behaviour implementation for ducks that fly<br>type FlyWithWings struct{}<br><br>// FlyWithWings method<br>func (fww FlyWithWings) Fly() {<br> fmt.Println(&quot;I&#39;m flying!&quot;)<br>}<br><br>// Flying behaviour implementation for ducks that do not fly<br>type FlyNoWay struct{}<br><br>// FlyNoWay method<br>func (fnw FlyNoWay) Fly() {<br> fmt.Println(&quot;I can&#39;t fly!&quot;)<br>}</pre><ul><li>QuackBehaviour set of classes</li></ul><pre>// QuackBehavior interface that all quacking behaviour classes implement<br>type QuackBehaviour interface {<br> Quack()<br>}<br><br>// QuackBehavior implementation for ducks that quack<br>type Quack struct{}<br><br>// Quack method<br>func (q Quack) Quack() {<br> fmt.Println(&quot;Quack!&quot;)<br>}<br><br>// QuackBehavior implementation for ducks that squeak<br>type Squeak struct{}<br><br>// Squeak method<br>func (s Squeak) Quack() {<br> fmt.Println(&quot;Squeak!&quot;)<br>}<br><br>// QuackBehavior implementation for ducks that don&#39;t quack<br>type MuteQuack struct{}<br><br>// MuteQuack method<br>func (mq MuteQuack) Quack() {<br> fmt.Println(&quot;Silence!&quot;)<br>}</pre><ul><li>Duck Class</li></ul><pre>// Declare two reference variables for the behaviour interface types.<br>// All duck subclasses inherit these.<br>type Duck struct {<br>  flyBehaviour   FlyBehaviour<br>  quackBehaviour QuackBehaviour<br>}<br><br>// Delegate fly and quack behaviour to respective behaviour classes<br>func (d Duck) PerformFly() {<br> d.flyBehaviour.Fly()<br>}<br><br>func (d Duck) PerformQuack() {<br> d.quackBehaviour.Quack()<br>}<br><br>// Setting/Changing the behaviour dynamically<br>func (d *Duck) SetFlyBehaviour(fb FlyBehaviour) {<br>   d.flyBehaviour = fb<br>}<br><br>func (d *Duck) SetQuackBehaviour(qb QuackBehaviour) {<br>   d.quackBehaviour = qb<br>}</pre><ul><li>Integrating with Duck subclasses</li></ul><pre>// MallardDuck struct<br>type MallardDuck struct {<br> Duck<br>}<br><br>// MallardDuck constructor<br>func NewMallardDuck() *MallardDuck {<br> mallard := &amp;MallardDuck{}<br> mallard.flyBehaviour = FlyWithWings{}<br> mallard.quackBehaviour = Quack{}<br> return mallard<br>}<br><br>// RubberDuck struct<br>type RubberDuck struct {<br> Duck<br>}<br><br>// RubberDuck constructor<br>func NewRubberDuck() *RubberDuck {<br> rubber := &amp;RubberDuck{}<br> rubber.flyBehaviour = FlyNoWay{}<br> rubber.quackBehaviour = Squeak{}<br> return rubber<br>}</pre><ul><li>Testing the Duck Code</li></ul><pre>func main() {<br> mallard := NewMallardDuck()<br> mallard.PerformFly()<br> mallard.PerformQuack()<br><br> rubber := NewRubberDuck()<br> rubber.PerformFly()<br> rubber.PerformQuack()<br>}</pre><ul><li>Run the code!</li></ul><pre>I&#39;m flying!<br>Quack!<br>I can&#39;t fly!<br>Squeak!</pre><ul><li>Creating new FlyBehaviour</li></ul><pre>// Rocket-powered flying behaviour<br>type FlyRocketPowered struct{}<br><br>// FlyRocketPowered method<br>func (frp FlyRocketPowered) Fly() {<br> fmt.Println(&quot;I&#39;m flying with a rocket!&quot;)<br>}</pre><ul><li>Changing behaviour dynamically</li></ul><pre>func main() {<br> mallard := NewMallardDuck()<br> mallard.PerformFly()<br> mallard.PerformQuack()<br><br> rubber := NewRubberDuck()<br> rubber.PerformFly()<br> rubber.PerformQuack()<br><br> rubber.SetFlyBehaviour(FlyRocketPowered{})<br> rubber.PerformFly()<br> rubber.SetQuackBehaviour(MuteQuack{})<br> rubber.PerformQuack()<br>}</pre><ul><li>Run the code!</li></ul><pre>I&#39;m flying!<br>Quack!<br>I can&#39;t fly!<br>Squeak!<br>I&#39;m flying with a rocket!<br>Silence!</pre><h4><strong>SUMMARY</strong></h4><ul><li><strong>OO Basics — </strong>Abstraction, Encapsulation, Polymorphism, Inheritance.</li><li><strong>OO Principles</strong></li></ul><blockquote>Design Principle 1: Identify the aspects of your application that vary and separate them from what stays the same.</blockquote><blockquote>Design Principle 2: Program to an interface, not an implementation.</blockquote><blockquote>Design Principle 3: Favour composition (HAS-A relationship) over inheritance (IS-A relationship)</blockquote><ul><li><strong>OO Patterns</strong></li></ul><p>Strategy — defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.</p><p><em>Next : </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc"><em>Keeping your Objects in the know: the Observer Pattern</em></a></p><p><em>Source Code : </em><a href="https://github.com/pi-sin/head-first-design-patterns-in-golang"><em>https://github.com/pi-sin/head-first-design-patterns-in-golang</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cbd940e113a" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Head First Design Patterns using Go — 1. Welcome to Design Patterns: the Strategy Pattern</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Design Patterns using Go — Introduction]]></title>
            <link>https://faun.pub/head-first-design-patterns-using-go-introduction-d9f05a4c243a?source=rss-743cc8729c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f05a4c243a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Piyush Sinha]]></dc:creator>
            <pubDate>Mon, 03 May 2021 21:18:38 GMT</pubDate>
            <atom:updated>2023-07-02T20:01:04.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>Head First Design Patterns using Go —1. Introduction</h3><h4>A comprehensive series exploring design patterns, inspired by the O’Reilly book of the same name, adapted from Java to Go.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IB0ykdItJ3oRroEbAvnM_Q.png" /></figure><p><strong>Table of Contents</strong></p><ol><li><strong>Introduction</strong></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a">Welcome to Design Patterns: the Strategy Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-keeping-your-objects-in-the-know-the-observer-pattern-948e6b5b66fc">Keeping your Objects in the know: the Observer Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-3-decorating-objects-the-decorator-pattern-c35636722da7">Decorating Objects: the Decorator Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-4-baking-with-oo-goodness-the-factory-pattern-181bbbf4a8fb">Baking with OO goodness: the Factory Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-5-encapsulating-invocation-the-command-pattern-2f8c0a79d1c7">Encapsulating Invocation: the Command Pattern</a></li><li><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-6-being-adaptive-the-adapter-and-facade-patterns-c6361a602c3a">Being Adaptive: the Adapter and Facade Patterns</a></li><li>Encapsulating Algorithms: the Template Method Pattern</li><li>Well-managed Collections: the Iterator and Composite Patterns</li><li>The State of Things: the State Pattern</li><li>Controlling Object Access: the Proxy Pattern</li><li>Patterns of Patterns: Compound Patterns</li></ol><blockquote>This series of articles will run you by the design patterns the way it is explained in the Head First Design Patterns book using Go as the coding language.</blockquote><p>Before I start, let me briefly explain why I began writing this series of articles.</p><h4>What’s so special about design patterns?</h4><p>You know you don’t want to reinvent the wheel (or worse, a flat tire), so you look to design patterns — the lessons learned by those who’ve faced the same software design problems. With design patterns, you get to take advantage of the best practices and experience of others, so that you can create functional, elegant, extensible, reusable, and flexible software.</p><p>When it comes to exploring design patterns, no resource matches the exceptional standards set by ‘<a href="https://www.amazon.in/First-Design-Patterns-Brain-Friendly/dp/0596007124/ref=sr_1_2?adgrpid=58133433599&amp;dchild=1&amp;ext_vrnc=hi&amp;gclid=Cj0KCQjw4cOEBhDMARIsAA3XDRgtwp9MvWZA8Et5QDONt9pFRfmiWE5ocAM0opa_QVXeNHUAuVCY4pEaAvzaEALw_wcB&amp;hvadid=356409287470&amp;hvdev=c&amp;hvlocphy=9062008&amp;hvnetw=g&amp;hvqmt=e&amp;hvrand=7869959171043106429&amp;hvtargid=kwd-298757005182&amp;hydadcr=25367_2099520&amp;keywords=head+first+design+patterns&amp;qid=1620118354&amp;sr=8-2"><strong>Head First Design Patterns</strong></a>’ from O’Reily.</p><p>The book’s disruptive writing style — featuring visual aids, conversational tone, practical examples, and incremental solutions — sets it apart, engaging readers on intellectual and emotional levels.</p><p>Believe it or not, I searched extensively but couldn’t find any resources on the internet that come close to matching the exceptional quality of the above book when it comes to explaining design patterns using Go. Therefore, I started this pet project of adapting the Head First Design examples, which is written in JAVA, to Go.</p><h4>I am thrilled to present this series of articles, aiming to convey the concepts of design patterns in a concise yet comprehensive manner, employing Go as the primary programming language.</h4><h4><strong>Throughout this series, you will learn:</strong></h4><ul><li>Design patterns that truly matter, carefully selected for their practicality and effectiveness</li><li>When and why to employ these patterns, gaining a deep understanding of their purpose and benefits</li><li>How to apply the patterns to your own software designs, fostering flexibility and reusability</li><li>Recognizing scenarios where using patterns may not be advantageous (avoiding pattern fever) and making informed decisions</li><li>Underlying object-oriented design principles upon which these patterns are founded, cultivating a holistic approach to software design</li></ul><p>Let the learning begin…</p><p><em>Next: </em><a href="https://pi-sin0.medium.com/head-first-design-patterns-using-go-1-welcome-to-design-patterns-the-strategy-pattern-6cbd940e113a"><em>Welcome to Design Patterns: the Strategy Pattern</em></a></p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f05a4c243a" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/head-first-design-patterns-using-go-introduction-d9f05a4c243a">Head First Design Patterns using Go — Introduction</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>