<?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[Wenchin Rolls Around - Medium]]></title>
        <description><![CDATA[A blog on software engineering, product management &amp; other stuff - Medium]]></description>
        <link>https://medium.com/wenchin-rolls-around?source=rss----ea7d514cd62c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Wenchin Rolls Around - Medium</title>
            <link>https://medium.com/wenchin-rolls-around?source=rss----ea7d514cd62c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:48:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/wenchin-rolls-around" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[淺入淺出 Dependency Injection]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E6%B7%BA%E5%85%A5%E6%B7%BA%E5%87%BA-dependency-injection-ea672ba033ca?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea672ba033ca</guid>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[依賴注入]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sat, 08 May 2021 13:56:24 GMT</pubDate>
            <atom:updated>2021-06-09T02:14:59.738Z</atom:updated>
            <content:encoded><![CDATA[<h4>DI 有什麼好？如何實作 DI？DI 到底是什麼？</h4><p>相信很多人對 Dependency Injection（DI，依賴注入）的觀念有很多疑惑。從最根本的本質（到底它是個技術？工具？設計模式？還是信仰？）、到目的（注入一堆東西是為了單元測試好寫嗎？）、到引入的手段（是不是要學會用 DI container 才能實現 DI？）等，都很容易讓人寫著寫著就黑人問號了。</p><p>因為我也很問號（尤其一開始就碰 MS DI 有夠不解），所以有次在一個 Backend 隨意聊的分享場合就決定講這主題，逼自己好好研讀大神同事 J 借我的書—「<a href="https://www.books.com.tw/products/0010865153?gclid=CjwKCAjwhMmEBhBwEiwAXwFoEehAlibs1ZQTWNxYc5Nys2kDo54ghf90DxcFMO7bgV_inEgT511gLhoCFPoQAvD_BwE">依賴注入：原理、實作與設計模式 by Steven van Deursen, Mark Seemann</a>」這本經典，好好坐下來認識 DI，並跟大家討論我的理解，假日順手整理成文章。目的是學好 DI 架構、一起寫出更舒服的程式碼。</p><h3>大綱</h3><ol><li>Why: 為什麼使用介面 (interface) 去設計程式、為什麼需要 DI</li><li>How: 如何實作 DI</li><li>What: DI 定義、跟 IoC（控制反轉）和 DIP（依賴反轉原則）的關係、優缺點</li><li>常見 DI 設計模式</li></ol><p>本文僅討論概念、基本實作 pure DI 架構，不討論使用 DI 容器等依照不同語言有不同工具的情境。</p><h3>Disclaimer</h3><p>DI 架構本身要解決的問題不限 OO（物件導向）領域，但以下會聊到的解決方案都屬於 OOP 語言的領域，範例也是用 C# 寫的。</p><p>DI 不適用於程序式程式設計；DI 對函數式程式設計、動態程式語言也無法發揮全力。雖然如此，DI 架構與很多軟體設計中的實務原則、設計模式也有相關。</p><h3>Why use DI?</h3><h4>如何向一個五歲孩子解釋何謂 DI?</h4><p><a href="https://www.books.com.tw/products/0010865153?gclid=CjwKCAjwhMmEBhBwEiwAXwFoEehAlibs1ZQTWNxYc5Nys2kDo54ghf90DxcFMO7bgV_inEgT511gLhoCFPoQAvD_BwE">依賴注入：原理、實作與設計模式</a>書中提到 Stack Overflow 上面 John Munsch 舉的<a href="https://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old">例子</a>，DI 就是：</p><blockquote>When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired.</blockquote><blockquote>What you should be doing is stating a need, “I need something to drink with lunch,” and then we will make sure you have something when you sit down to eat.</blockquote><p>如果你跟我一樣還沒有小孩，體驗可能沒那麼深刻，那我們看下一個例子。</p><h4>如何稱呼男/女友？你都叫他他的名字還是「寶貝」？</h4><p>如果叫的是「寶貝」，那恭喜你，你是 DI 大師 👍</p><p>因為你使用了介面（「寶貝」稱呼）而非實作（不同的名字），即使換了男/女友（抽換不同的實作）也都不用改稱謂。</p><h4>插座（介面）允許不同電器的插頭（實作）</h4><ul><li>緊耦合：就像廉價旅館直接用電線連進牆壁上一個洞的吹風機，無法替換電器、難以修改</li><li>鬆耦合：就像插座，可以替換吹風機、筆電插頭等，符合 SOLID 裡面的里氏替換原則 (Liskov Substitution Principle)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J57XjBBcYJ26QETwnkfpqA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>As long as the plug (the implementation) fits into the socket (implements the interface), and it can handle the amount of volts and hertz (obeys the interface contract), we can combine appliances in a variety of ways.</blockquote><h4>插頭怎麼實現 SOLID 的一些原則？</h4><ul><li>里氏替換原則 (Liskov Substitution Principle)：插座在電腦出現數十年之前就誕生了，但插座最早的設計者不可能預見未來個人電腦的盛行。在插座發明後，即可在不需要對插座更動的情況下，切換各種連接插頭的電器。里氏替換原則就是對介面的實作要能替換，而且不須破壞客戶端介面或實作。</li><li>開放封閉原則 (Open Close Principle)：只要個人電腦的插頭遵循插座要求的規格設計它們的插頭，就可以在不用修改插座設計（既有系統 code base）的情況下使用這個它。鬆耦合架構對「開放（擴展）封閉（修改）原則」有幫助！</li></ul><h4>從插座的故事我們學到了…</h4><blockquote>Program to an interface, not an implementation.</blockquote><p>既然介面這麼棒，我們就寫個介面初始化來用吧？</p><pre>IMessageWriter writer = new IMessageWriter(); // WRONG!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uifaf_YqS4RbAMi3eU0a1A.png" /></figure><p>因為介面不包含實作，無法這樣直接成立一個介面的物件，需要透過別的管道建立。而本文的主角 DI 可以解決這個問題！</p><h3>How do I use DI?</h3><h4>簡單，就是學會用 DI 容器對吧？</h4><p>DI containers 是種函式庫，讓你可以在構成一個應用程式的時候更容易的實作 DI、組織類別，但絕對不是必要的選擇。</p><p>應該學習的方式是先學會實作 pure DI、再按照需求使用 DI containers。</p><h4>寫個 Socket 類別，實作插頭介面！</h4><p>說了這麼多，總是要寫點程式碼，不然沒感覺。</p><p>就用前面的插座來寫吧（本來我用別的例子，但感謝學妹 V 的建議換了插座呼應舉的例 👆）。以下的插座範例程式碼可以在這個 repo 找到：</p><p><a href="https://github.com/wenchin77/di-is-difficult/tree/master/Socket">wenchin77/di-is-difficult</a></p><p>首先我們定義插頭的介面 IElectricalPlug，讓他有個方法 Connect()，意即插插座連接到電源：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94a15b2c3ecce19d152784b7ea271056/href">https://medium.com/media/94a15b2c3ecce19d152784b7ea271056/href</a></iframe><p>然後定義使用插頭的「插座」類別 Socket，透過「建構子注入」把 IElectricalPlug 注進這個類別。所以在做 SendPower() 這件事的時候，可以呼叫插頭的實作去做 Connect()，之所以可以呼叫是因為實作 IElectricalPlug 介面的類別一定要先實作 Connect() 這方法！</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37071f495af82c76e69c4465a1cc4003/href">https://medium.com/media/37071f495af82c76e69c4465a1cc4003/href</a></iframe><p>廢話不多說，我們馬上就來實作一個吹風機插座類別 HairDryerPlug，這邊簡化為印一行字代表它連接上電源：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1310d9afd4c46ecf7d55d6966c1db36/href">https://medium.com/media/b1310d9afd4c46ecf7d55d6966c1db36/href</a></iframe><p>現在可以明顯感受到 Socket 依賴介面 IElectricalPlug，不會知道實作是哪位。</p><p>呼叫一下：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95709409955bad574cfc8f6c587a7263/href">https://medium.com/media/95709409955bad574cfc8f6c587a7263/href</a></iframe><p>Console 結果為：</p><pre>使用吹風機插頭<br>HairDryerPlug connected!</pre><p>今天我們寫的是 HairDryerPlug ，改天有了別的需求可以寫 LaptopPlug 、PhonePlug 等等不同的插頭類別，只要確保有實作 IElectricalPlug 介面。</p><p>而注入不同的 IElectricalPlug 類別實作就會有不同的 Connect() 方法實作細節，在不需要動到 Socket 程式碼的情況下，即可抽換實際連結的插頭物件。</p><h3>What’s DI?</h3><blockquote><em>所謂的 DI 架構，指的是一整套設計模式與實務原則。這是一種程式設計面上的思維訓練，而不是特指某種技術。DI 架構的最後目標，是在物件導向程式的領域中，打造出具備高可維護性的軟體。</em></blockquote><p>DI 其實是個手段，不是目標。</p><p>為什麼這麼說呢？因為透過 DI，我們希望做到鬆耦合的架構，提高程式的可維護性。一旦程式的可維護性高，效率就會提升，開發的產出也會提升，而達到我們的目的，也就是金錢和快樂。</p><pre>DI → 鬆耦合 → 高可維護性 → 程式效率高 → 😃 + 💰</pre><blockquote>DI isn’t an end goal — it’s a means to an end. DI enables loose coupling, and loose coupling makes code more maintainable.</blockquote><h4>「依賴」是啥？「注入」又是啥？</h4><p>四月上了 Bill 的<a href="https://skilltree.my/events/2021/4/10/oop-batch-19">輕鬆學會物件導向課程</a>，他拆解「依賴注入」這個神祕名詞的方法和例子滿有趣的：</p><ul><li>依賴 = 耦合 → 兩個物件是否認識彼此</li><li>注入 = 這個認識的關係怎麼建立的，也就是認識的途徑</li></ul><p>以愛情為例：兩人的關係就是依賴，注入方式可能有路上搭訕注入、交友網站注入、相親注入…等。</p><h4>DI 的 3 個主要職責</h4><ol><li>創建物件（最重要！）</li><li>知道哪些類別需要被創建的那些物件</li><li>提供類別所有它需要才能正常運作的物件</li></ol><p>也就是說，DI 分散了物件「創建」和「使用」的職責，於是依賴的類別可以被改變，而被依賴的類別不會知道或在意（因為被依賴類別的物件 IElectricalPlug 不是 Socket 創建的，是被注入的），只要知道它可以怎麼被用（以上面的例子就是呼叫 Connect() 方法）就好了。</p><blockquote><em>The goal of dependency injection is to separate the usage an object from it’s creation. This removes a class’s direct dependency on another class. Dependent classes can be changed out without the depending class knowing or caring.</em></blockquote><h4>請問你跟控制反轉 (IoC) 的關係是……？</h4><p>Inversion of Control （控制反轉）是實現低耦合的最佳設計方式之一，讓通用的程式碼來控制應用特定的程式碼，相依於抽象而不倚賴實作。</p><p>實現 IoC 的做法有：DI（例如我需要車子類別不直接用實作，而是注入 ICar 介面）、工廠模式（拉個 CarFactory 類別把控制產生執行個體如 Benz, BMW 類別的權力移轉給工廠，再由工廠拿車）……等。</p><p>結論：IoC 的範疇包含 DI，但不僅限於 DI。</p><h4>請問你跟依賴反轉原則 (DIP) 的關係是……？</h4><p>SOLID 原則之一的 Dependency Inversion Principle（依賴反轉原則）強調用抽象解耦依賴關係：</p><blockquote>High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g., interfaces).</blockquote><blockquote>Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.</blockquote><p>DIP 是個使用抽象時依賴關係的準則或概念，IoC 說明了依賴關係的控制方向，而 DI 是一種處理依賴關係的模式。</p><p>有興趣的人可以參考 Martin Fowler 的 <a href="https://martinfowler.com/articles/dipInTheWild.html#YouMeanDependencyInversionRight">DIP in the Wild 的 You mean Dependency Inversion, Right?</a> 段落。這裡劇透一下結論：</p><blockquote>DI is about how one object acquires a dependency. When a dependency is provided externally, then the system is using DI. IoC is about who initiates the call. If your code initiates a call, it is not IoC, if the container/system/library calls back into code that you provided it, is it IoC.</blockquote><blockquote>DIP, on the other hand, is about the level of the abstraction in the messages sent from your code to the thing it is calling. To be sure, using DI or IoC with DIP tends to be more expressive, powerful and domain-aligned, but they are about different dimensions, or forces, in an overall problem. DI is about wiring, IoC is about direction, and DIP is about shape.</blockquote><h4>DI 的優點</h4><ol><li>Late binding：</li></ol><p>例如可以較容易的替換資料庫（SQL Server 要換成 PostgreSQL 等）。</p><p>2. Extensibility：</p><p>假設我們現在插頭的例子有了新需求：希望吹風機插頭有個驗證身分的過程，確認是媽媽才能用，以免小孩亂玩。</p><p>根據上面插頭的例子，我們可以用先前定義的 IElectricalPlug 介面新開一個 SecureHairDryerPlug 類別：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613d800138a80c983dbebf009d897380/href">https://medium.com/media/613d800138a80c983dbebf009d897380/href</a></iframe><p>以上用裝飾者模式把本來的吹風機插頭傳進來，驗證無誤才呼叫它 Connect() ，輕鬆寫意。</p><p>呼叫一下哪次不呼叫：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c37cfd4db781e35dcdbe306b3ec9db/href">https://medium.com/media/f0c37cfd4db781e35dcdbe306b3ec9db/href</a></iframe><p>Console 結果：</p><pre>使用吹風機插頭<br>HairDryerPlug connected!</pre><pre>使用經身分驗證的安全吹風機插頭<br>SecureHairDryerPlug: identity verified.<br>HairDryerPlug connected!</pre><p>3. Parallel development</p><p>多人開發時，把你的模組 DI 到我的應用，定義好簽章就可以各自開發、驗證，一切順利。</p><p>4. Maintainability</p><p>實現 SOLID 裡面的 SRP 原則，幫類別區分職責。</p><p>5. Testablility</p><p>寫程式一定要有測試，讓我們為剛剛辛苦寫的插座寫個單元測試吧！</p><p>因為有 DI 插頭，所以我們首先寫個假的 IElectricalPlug 實作，讓我們叫它 TestSpyPlug 好了。它就簡單的寫成監看 Connect() 方法有沒有被呼叫。</p><blockquote>Test Spy 型的實體類別：驗證 sut 對其他元件的間接輸出呼叫行為</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/442598fe7d28db28a0218072c67090a3/href">https://medium.com/media/442598fe7d28db28a0218072c67090a3/href</a></iframe><p>然後在 SocketTests 寫個測試替身（SUT, system under test），取代原本物件。</p><p>最後用 TestSpyPlug 注入 Socket class 寫插座的單元測試：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/937927de63d0ecc5f5403fd69b995ffe/href">https://medium.com/media/937927de63d0ecc5f5403fd69b995ffe/href</a></iframe><p>乾淨俐落，不被插頭影響（當然插頭應該另外有單元測試的），優秀！</p><h4>DI 的缺點</h4><ol><li>系統架構的複雜度增加，追扣較難：由於程式不再和實作的類別相關，因此開發者追程式碼時會比較困難。這需要花時間來熟悉整體系統的運作、還有熟悉 IDE（VSCode 就要常常按 F12 —切換定義和實作的快捷鍵）才會上手。</li><li>所需寫的程式碼變多，開發速度變長：為了這個架構，得要多寫一些程式；這會直接的影響到開發的速度。</li><li>往往某種程度上耦合了你用的 DI 框架，或你決定實現 DI 的方式。</li></ol><h4>誰適合注入？誰不適合注入？</h4><p>首先要了解依賴性的穩定程度：</p><ol><li>Stable dependencies（穩定依賴性）：不用另外準備、安裝、版本更新會向下相容、有可預期的演算法/行為模式、你不會想替換/包裝/裝飾/中介攔截這些類別或模組。例如：大部分 .NET 基礎類別庫 (BCL) 的型別。</li><li>Volatile dependencies（不穩定依賴性）：應用程式需要準備或 configure runtime 環境、還沒開發完、不是所有設備都安裝這份依賴性關係對象（可能會很貴）、依賴性關係對象有無法被預期的行為模式（需要單元測試保護）。例如：BCL 函式庫的 DB 設定相關功能 → 隔離才有機會改用其他資料庫、需要依賴外部資源才能完成操作的 MQ、經過網路的服務、對檔案系統的操作等。</li></ol><p>不穩定的更需要採用 DI 架構：</p><blockquote><em>Volatile Dependencies are the focal point of DI. It’s for Volatile Dependencies rather than Stable Dependencies that you introduce Seams into your application. Again, this obligates you to compose them using DI.</em></blockquote><h4>物件的生命週期 (Object Lifetime)</h4><p>當類別喪失對依賴性關係的控制權後，同時失去決定要使用哪份實體物件、何時建立物件、何時讓這物件失效的管理能力。</p><p>比較以下兩段的差異：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38e0d616914b3a9ef00d1a6a70bb418/href">https://medium.com/media/c38e0d616914b3a9ef00d1a6a70bb418/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08618e9f02d344bd817be27ff7dc80dd/href">https://medium.com/media/08618e9f02d344bd817be27ff7dc80dd/href</a></iframe><p>在 DI 裡，管理物件的生命週期 (lifetime management) 很重要！</p><h4>物件的攔截 (Interception)</h4><p>當我們把依賴性關係的控制權交給第三方，便可在物件交給使用方的類別之前先攔截、做更動。</p><p>例如剛剛寫的 SecureHairDryerPlug 就是對 HairDryerPlug 加以攔截。</p><h3>DI 設計模式</h3><p>DI 的設計模式包含並不限於以下幾種。</p><p>想必插座插頭的例子你看到這裡也膩了，以下讓我們以司機和車子的類別為例。</p><h4>建構子注入</h4><p>確保類別所需要的不穩定依賴對象即使不直接依賴、還是可以被滿足。是最通用的注入方式，也是我們在插座範例用的注入方式。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35d5afa0b34aad0a83868a5b94e37177/href">https://medium.com/media/35d5afa0b34aad0a83868a5b94e37177/href</a></iframe><h4>方法注入</h4><p>在同一類別、不同方法上注入不同的依賴對象。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa26fbeb62486486bcbb3ebe7298ae83/href">https://medium.com/media/fa26fbeb62486486bcbb3ebe7298ae83/href</a></iframe><h4>屬性注入</h4><p>當已經有適合的內建預設可用，但還是希望提供呼叫方一份彈性。要注意可能使用方忘記把屬性賦值就會出問題，適用於設計函式庫。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8445df9f75c27c9e81011a96dc63d17a/href">https://medium.com/media/8445df9f75c27c9e81011a96dc63d17a/href</a></iframe><p>DI 真的博大精深，還有很多還沒鑽研的延伸（例如物件生命週期實作、AOP 等等），待我研究有心得的話有機會寫個 part 2 繼續跟大家分享。</p><h3>在 AppWorks School - Backend 隨意聊分享的簡報</h3><p><a href="https://hackmd.io/@wenchin/rJwfTWoUd?type=slide#/">淺入淺出 DI - HackMD</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Fwenchin77%2Fbutton%2F&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fwenchin77&amp;image=https%3A%2F%2Fstatic.like.co%2Flikecoin_de-portrait.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="485" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href">https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href</a></iframe><h3>Reference</h3><ul><li><a href="https://www.books.com.tw/products/0010865153?gclid=CjwKCAjwhMmEBhBwEiwAXwFoEehAlibs1ZQTWNxYc5Nys2kDo54ghf90DxcFMO7bgV_inEgT511gLhoCFPoQAvD_BwE">依賴注入：原理、實作與設計模式</a></li><li><a href="https://skilltree.my/events/2021/4/10/oop-batch-19">輕鬆學會物件導向（使用C#） - SkillTree 我的技能樹</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fopen.spotify.com%2Fembed-podcast%2Fepisode%2F27EhYYkhLjyMwHFD4VJk0X&amp;display_name=Spotify&amp;url=https%3A%2F%2Fopen.spotify.com%2Fepisode%2F27EhYYkhLjyMwHFD4VJk0X&amp;image=https%3A%2F%2Fi.scdn.co%2Fimage%2F32c1df2d270bbb048a4e9e4a8e132a279f789e36&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=spotify" width="600" height="232" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd618e91afa0fecdf223523cdec6eca/href">https://medium.com/media/fdd618e91afa0fecdf223523cdec6eca/href</a></iframe><ul><li><a href="https://completedeveloperpodcast.com/episode-185/">Dependency Injection | Complete Developer Podcast</a></li><li><a href="https://martinfowler.com/articles/dipInTheWild.html#YouMeanDependencyInversionRight">DIP in the Wild</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea672ba033ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E6%B7%BA%E5%85%A5%E6%B7%BA%E5%87%BA-dependency-injection-ea672ba033ca">淺入淺出 Dependency Injection</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[軟體版本號]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E8%BB%9F%E9%AB%94%E7%89%88%E6%9C%AC%E8%99%9F-ee446e1ad543?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ee446e1ad543</guid>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[software-version-control]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 12:52:18 GMT</pubDate>
            <atom:updated>2026-09-20T10:47:18.357Z</atom:updated>
            <content:encoded><![CDATA[<h4>1.0.0 小數點那麼多在幹嘛？Breaking change 要 break 什麼？向下相容是要跟誰相容？</h4><p>今天我推了一份扣，新增了 DB 某表格的欄位，發完 PR 沒過多久，我準備戴上耳機聽音樂。這時幫我 code review 的資深同事走到我旁邊坐下說：「你剛剛給我那包扣啊，有動到 DB schema，想跟你確認這要上 production 嗎？」</p><p>我誠惶誠恐的放下耳機：「可能要欸，因為之後前端還要接這支 API 回傳的東西，需要用更新的版本。」</p><p>「喔那如果這次要上線，就會有 breaking change……。」他說，「你先輸出這次更動的 script，我先上 script 再上扣。因為如果 script 沒先上直接上最新版號的扣，程式跟 DB 要東西要不到就可能炸掉。但因為你這次只新增欄位，對沒更版的人來說也是可以向下相容。」</p><p>修但幾咧……版號？Breaking change？向下相容？</p><p>身為菜雞工程師，每當聽到同事在講專有名詞自然要 Google 一下。所以今天在這筆記一下 Software Versioning，也就是軟體版本號這件事。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfMzA8OjRdh1cXTJtwkTbA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fotofyn?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Laugesen</a> on <a href="https://unsplash.com/s/photos/numbers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>為何要有版本號？</h3><p>因為軟體會不斷進化、迭代。</p><p>假設我們推出一個 API（或是套件、服務）讓客戶使用，如果沒有壓上版本號，客戶順利的使用了第一個版本後，我們在第二個版本可能調整了呼叫 API 的輸入、輸出介面或參數。我們通知客戶使用新版何時會上線，這時候客戶如果沒有在版本更新時將所有 request response 根據最新版本規格調整好，就會出現與新版本系統不相容的狀況。甚至即使客戶馬上將所有 request response 調整了，也可能因為舊版的一些 request 還沒跑完但系統已經更新而發生錯誤。</p><p>因為要兼容不同版本的系統使用，所以有了版本號這個東西。也就是說，系統的使用者或客戶在軟體更版的時候，得以辨識他們拿到的系統版本是哪一版，做對應的處理（可能分開處理升級與尚未升級的部分）。</p><p>作為一名專業的開發者、或是一間專業的軟體服務提供者，如果改變對你的使用者是重要的，就要透過版號真實傳達修訂的意義。</p><p>保持專案高效率的一個重要部分是掌控軟體複雜度，如果今天沒有人知道使用你的軟體哪些函數可以可靠的呼叫，就無法好好的控制複雜度。</p><p>事實上，生活處處皆版號，例如我現在打文章用的 macOS 是 Big Sur 版本是 11.2.1、我上班的 Windows 版本是 Windows 10、我的 Python 版本是 3.8.7、同事借我的計算機概論是第 4 版（這個的意義應該就跟軟硬體不大相同了，但提供辨識版本別的機制這主軸類似）……。</p><p>而相容性 (compatibility) 就是系統發生變更後表現一致的特性。</p><h3>向下相容？那有沒有向上相容？</h3><p>有喔哪次沒有。不喜歡「上下」也沒關係，我們還可以用「前後」講同一件事。</p><blockquote><strong>Backward compatibility</strong> is a property of a system, product, or technology that allows for <a href="https://en.wikipedia.org/wiki/Interoperability">interoperability</a> with an older <a href="https://en.wikipedia.org/wiki/Legacy_system">legacy system</a>, or with <a href="https://en.wikipedia.org/wiki/Input/output">input</a> designed for such a system, especially in <a href="https://en.wikipedia.org/wiki/Telecommunications">telecommunications</a> and <a href="https://en.wikipedia.org/wiki/Computing">computing</a>.</blockquote><blockquote>A complementary concept is <a href="https://en.wikipedia.org/wiki/Forward_compatibility"><strong>forward compatibility</strong></a>. A design that is forward-compatible usually has a <a href="https://en.wikipedia.org/wiki/Technology_roadmap">roadmap</a> for compatibility with future standards and products.</blockquote><p>其實滿好理解的：</p><ul><li>向下相容 (Downward compatibility) = 向後相容 (Backward compatibility)：意指當系統（如程式、library 等）更新後，使用較落後版本建立的檔案、系統仍可以在新的系統中正常使用，或用舊版本仍可正常編譯執行</li><li>向上相容 (Upward compatibility) = 向前相容 (Forward compatibility)：意指舊版本系統（如程式、library 等）可以支援新版本的資料或服務</li></ul><h3>那 Breaking change 是在 break 什麼？</h3><blockquote>Modifying a system in a way that does not allow backward compatibility is sometimes called “<a href="https://en.wiktionary.org/wiki/breaking_change">breaking</a>” backward compatibility.</blockquote><p>會讓舊版程式無法正常運作的更新，就是一個 breaking change，也就是說在這個更新之後無法向後相容。</p><p>所以這裡的 break 是在打破「向後相容性」。</p><h3>版本號怎麼訂？</h3><p>基本上，你的團隊開心（可以正確理解、遵循）就好。</p><p>看看前人的訂法：</p><ul><li><a href="https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions">Windows 版本</a></li><li><a href="https://en.wikipedia.org/wiki/List_of_Apple_operating_systems">Apple OS 版本</a></li><li><a href="https://en.wikipedia.org/wiki/History_of_Python">Python 版本</a>：用 <a href="https://www.python.org/dev/peps/pep-0440/">PEP 440 — Version Identification and Dependency Specification</a> 訂定版號</li></ul><p>但如果希望使用一個比較正規的訂定方法，可以參考許多開發者常用的 &quot;semantic versioning&quot;。</p><h4>Semantic Versioning</h4><p>這個版本制定格式中文翻譯為「語意化版本」，是由 <a href="https://tom.preston-werner.com/">Tom Preston-Werner</a> 提出的版本號訂製規則。</p><blockquote>A meaningful method for incrementing version numbers.</blockquote><p>按照 <a href="https://semver.org/">Semantic Versioning 文件</a>，版本格式定義如下：</p><pre>MAJOR.MINOR.PATCH</pre><p>也就是「主版號.次版號.修訂號」，例如：1.0.0。</p><p>而版號遞增規則如下：</p><ol><li>主版號：當你做了不相容的 API 修改，</li><li>次版號：當你做了向下相容的功能性新增，</li><li>修訂號：當你做了向下相容的問題修正。</li></ol><p>先行版號及版本編譯資訊可以加到「主版號.次版號.修訂號」的後面，作為延伸。</p><p>文件裡面也有提到關於 0.y.z 初始開發階段版本控制怎麼處理、判斷發布 1.0.0 版本的時機、不小心把不相容的改版當成次版號發行怎麼辦……等問答，有興趣的人可以參考！</p><h3>Reference</h3><ul><li><a href="https://en.wikipedia.org/wiki/Software_versioning">Software versioning - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Backward_compatibility">Backward compatibility - Wikipedia</a></li><li><a href="https://semver.org/">Semantic Versioning 2.0.0</a></li><li><a href="https://www.slmt.tw/blog/2015/07/19/version-number-naming-convention/">版本編號的命名規則</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee446e1ad543" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E8%BB%9F%E9%AB%94%E7%89%88%E6%9C%AC%E8%99%9F-ee446e1ad543">軟體版本號</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[試玩 IPFS]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E8%A9%A6%E7%8E%A9-ipfs-a69a52abb954?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/a69a52abb954</guid>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[ipfs]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 11:56:17 GMT</pubDate>
            <atom:updated>2021-02-19T12:58:54.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>實現分散式儲存的星際檔案傳輸協定</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCFDDzRri5TbYnRWefOV9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jeremythomasphoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jeremy Thomas</a> on <a href="https://unsplash.com/s/photos/galaxy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>IPFS (InterPlanetary File System) 是什麼？</h3><blockquote>A peer-to-peer hypermedia protocol designed to make the web faster, safer, and more open.</blockquote><p>有鑒於 HTTP 協議在儲存檔案方面成本高、效率低、內容可能消失等特性， IPFS 是一個用 <a href="https://en.wikipedia.org/wiki/Peer-to-peer">peer-to-peer (P2P)</a> 架構設計出來的協議，目的是讓檔案儲存也能做到去中心化。</p><blockquote>如果你對區塊鏈有興趣，你應該要了解 IPFS ，區塊鏈本身是一項去中心化的分散式資料庫系統，由於必須做到去中心化的程度，它本身僅是適合紀錄數字的簡單儲存系統，無法載入文件或是圖片。但區塊鏈技術若要成功商業化，則必須擁有更複雜的儲存系統，用來提供複雜程式、文件、圖片及影片的儲存功能，而 IPFS 能補足區塊鏈的儲存性能問題。</blockquote><blockquote>目前去中心化應用（DAPP）只有計算作為籌碼用的加密貨幣時才會動到區塊鏈，其餘網頁、文件以及程式碼仍然儲存在單一伺服器上，例如 AWS 、 GCP 這些平台，本質上仍是中心化的產品。</blockquote><blockquote>照理說 DAPP 不該仰賴中心化的儲存空間，一旦伺服器被關閉，所有的網頁內容也就跟著消失，無法滿足區塊鏈當初設計的初衷，為了補足區塊鏈當前的缺陷，「IPFS 星際檔案系統」(InterPlanetary File System) 被設計出來。</blockquote><blockquote>它能提供分散式的 P2P 網路儲存服務，每一個節點都掌握部份的分割檔案，一旦上傳成功，檔案將以「DAG 有向無環」的形式被紀錄在 Merkle Tree 上而且無法修改與刪除，每個檔案都有唯一的 HASH 值，允許使用者利用該唯一的 HASH 值訪問並下載檔案。</blockquote><p>IPFS 本身不是區塊鏈，而是一種 p2p 的超媒體協議，目的是在讓 web 更快、更安全、更開放，做法是會針對每個檔案給一個唯一的 hash 值，將檔案分散存放在不同節點，可以與區塊鏈配合操作。</p><p>這個影片講滿清楚的：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5Uj6uR3fp-U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5Uj6uR3fp-U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5Uj6uR3fp-U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8c1cfb0f29f295b9c19ee2e7665b3ee/href">https://medium.com/media/a8c1cfb0f29f295b9c19ee2e7665b3ee/href</a></iframe><h4>IPFS 重點功能盤點</h4><ol><li>每個檔案（包含它的 blocks）都有一個唯一加密的 hash 值。</li><li>在網絡中去除重複的檔案。</li><li>當你查看或下載檔案的時候，需要提供檔案的 hash 值，讓網絡去幫你找尋對應的內容。</li><li>你不需要記得所有的 hash。有個對人類可讀性比較友善的服務叫做 IPNS (InterPlanetary Name System)，它可以用人類可快速識別的命名，幫你對應回 IPFS 節點。</li></ol><h3>開始試玩 IPFS</h3><h4>設定與啟動</h4><p>在本地我建立了一個資料夾，結構如下。staging 是準備要放即將要 export 出去的檔案的地方。</p><pre>ipfs_test<br>|_ staging<br>|_ data</pre><p>我使用 docker 拉<a href="https://github.com/ipfs/go-ipfs">go-ipfs</a> image 啟動，並指定檔案 export 的路徑。</p><pre>export ipfs_staging=&lt;/absolute/path/to/somewhere/&gt;<br>export ipfs_data=&lt;/absolute/path/to/somewhere_else/&gt;<br>docker run -d --name ipfs_host -v $ipfs_staging:/export -v $ipfs_data:/data/ipfs -p 4001:4001 -p 4001:4001/udp -p 127.0.0.1:8080:8080 -p 127.0.0.1:5001:5001 ipfs/go-ipfs:latest</pre><p>如果要監看 logs，可以下：</p><pre>docker logs -f ipfs_host</pre><p>進入 container 做事：</p><pre>docker exec -it ipfs_host /bin/sh</pre><p>啟動後可以查看介面 <a href="http://localhost:5001/webui">http://localhost:5001/webui</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_hwd9iZnchwQY_HfeKcKQ.png" /><figcaption>IPFS web ui</figcaption></figure><h4>丟檔案並拿到 hash</h4><p>進入 container 後，把檔案（這裡以 0050 某時間的價格 csv 為例）丟到本地的 staging 資料夾，下 export指令把它上傳到 ipfs 並取得 hash 值。</p><pre>wenchin@Wenchins-MacBook-Pro ipfs_test % docker exec -it ipfs_host /bin/sh<br>/ # ipfs add -r /export/<br>added Qme356WUG3k4MrH13Vd5dgQnHJY6BpGe5fKZpguY3CzXaD export/STOCK_DAY_0050_202010.csv<br> 677 B / 677 B [=====================================================================================================================================] 100.00%<br>/ #</pre><h4>用 hash 去查看檔案</h4><p>查看剛剛丟的檔案：</p><pre>wenchin@Wenchins-MacBook-Pro ipfs_test % docker exec -it ipfs_host /bin/sh<br>/ # ipfs cat /ipfs/Qme356WUG3k4MrH13Vd5dgQnHJY6BpGe5fKZpguY3CzXaD<br>date,open,high,low,close<br>109/10/05,103.45,104.05,103,103.05<br>109/10/06,104,104.35,103.85,104.25<br>109/10/07,104,105,103.5,104.8<br>109/10/08,105.45,106.35,105.3,106.2<br>109/10/12,106.7,107.7,106.7,107.05<br>109/10/13,107.35,107.6,106.2,107.1<br>109/10/14,107.05,107.2,106.45,106.7<br>109/10/15,106.5,106.5,105.1,105.7<br>109/10/16,105.7,106.3,105.1,105.25<br>109/10/19,105.65,106.6,105.6,106.6<br>109/10/20,106.4,106.45,106,106<br>109/10/21,106,106.55,105.65,105.95<br>109/10/22,105.7,106.1,105.5,106.1<br>109/10/23,106.5,106.65,105.65,106.1<br>109/10/26,106.1,106.6,105.8,106.1<br>109/10/27,105.75,105.75,105.15,105.5<br>109/10/28,105.5,105.5,104.8,105<br>109/10/29,104,104.1,103.25,103.85<br>109/10/30,103.55,103.6,102.7,103</pre><p>也可以從這邊查看 <a href="http://127.0.0.1:8080/ipfs/Qme356WUG3k4MrH13Vd5dgQnHJY6BpGe5fKZpguY3CzXaD">http://127.0.0.1:8080/ipfs/Qme356WUG3k4MrH13Vd5dgQnHJY6BpGe5fKZpguY3CzXaD</a></p><h4>把我的 node 連結到 IPFS network</h4><p>IPFS daemon 起起來的時候，我的 local node 就會加入 IPFS 網絡了。</p><p>查詢自己的 id（以下指令結果舉例來自<a href="https://flyingzumwalt.gitbooks.io/decentralized-web-primer/content/going-online/lessons/connect-your-node.html">教學文件</a>）：</p><pre>wenchin@Wenchins-MacBook-Pro ipfs_test % docker exec -it ipfs_host /bin/sh<br>/# ipfs id<br>{<br>    &quot;ID&quot;: &quot;QmRX....xQTp&quot;,<br>    &quot;PublicKey&quot;: &quot;CAAS....AAE=&quot;,<br>    &quot;Addresses&quot;: [<br>        &quot;/ip4/127.0.0.1/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip4/12.2.0.36/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip6/::1/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip6/2802:285:8360:da70::9191/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip6/2802:285:8360:da70:5146:9a0a:e910:19c3/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip6/2802:285:8360:da70:ccb4:bd10:baa3:d022/tcp/4001/ipfs/QmRX....xQTp&quot;,<br>        &quot;/ip4/83.24.208.218/tcp/26521/ipfs/QmRX....xQTp&quot;<br>    ],<br>    &quot;AgentVersion&quot;: &quot;/go-ipfs/0.5.0-dev/17e886e29&quot;,<br>    &quot;ProtocolVersion&quot;: &quot;ipfs/0.1.0&quot;<br>}</pre><p>既然是 p2p，就也要可以尋找其他的 peers！</p><p>透過 command line:</p><pre>wenchin@Wenchins-MacBook-Pro ipfs_test % docker exec -it ipfs_host /bin/sh<br>/ # ipfs swarm peers<br>/ip4/159.89.140.62/tcp/31097/p2p/12D3KooWSYWSbnH3cgS9zCkmU5H7EqsJa3MF1Pe8NqjFLjePpjy2<br>/ip4/159.89.140.62/udp/31001/quic/p2p/12D3KooWQHzpV256bmVJa8zquCTZxEoNnifhducdBNnrmkPWwhZt<br>/ip4/159.89.140.62/udp/31009/quic/p2p/12D3KooWJKe38s4PezBchFQD9qs8j7yisJZtcj8bcoDuX6xX51Zt<br>/ip4/159.89.140.62/udp/31019/quic/p2p/12D3KooWDXd1X3J8iuc9nfkfkDZaFBtLeAXL3p7ebWXkEkuR2axy<br>/ip4/159.89.140.62/udp/31024/quic/p2p/12D3KooWGoncPAVoyPtHyDSn8nmLmCUZnybr4b8iV4VPxz677QeC<br>/ip4/159.89.140.62/udp/31025/quic/p2p/12D3KooWDU55nyCAz1ELDGwGyVtUdMYJPNQnMwCv23GAa2K23Ziz<br>...</pre><p>透過 web ui:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkLbo7Dhc2xmJ3-Q_gEx0A.png" /><figcaption>IPFS web ui — find peers</figcaption></figure><h4>查看別人的檔案</h4><p>可以透過自己的 IPFS 節點造訪別人的檔案內容。我們來看看被 IPFS 團隊放上 IPFS 網絡的土耳其文維基百科 snapshot！</p><blockquote>The IPFS team have published a snapshot of the turkish version of wikipedia. The hash of that snapshot, which contains about 15GB of Turkish-language wikipedia pages, is Qme2sLfe9ZMdiuWsEtajWMDzx6B7VbjzpSC2VWhtB6GoB1. We can use the command line to have your IPFS node read pages from that snapshot.</blockquote><pre>wenchin@Wenchins-MacBook-Pro ipfs_test % docker exec -it ipfs_host /bin/sh<br>/ # ipfs cat Qme2sLfe9ZMdiuWsEtajWMDzx6B7VbjzpSC2VWhtB6GoB1/wiki/Peer-to-peer.html &gt; Peer-to-peer.html</pre><p>查看土耳其文維基百科部分的檔案：</p><pre>/ # ipfs ls Qme2sLfe9ZMdiuWsEtajWMDzx6B7VbjzpSC2VWhtB6GoB1/wiki/Anasayfa.htm</pre><h3>後記</h3><p>去中心化一直是我覺得很有趣的概念，最近終於透過 IFPS 發現稍微玩了一下。以上是只玩了一些皮毛，體驗一下這個協議的操作。還有像是在 IPNS 發布檔案、處理檔案的 blocks、IPFS 模組工具等都還需要另外研究才會比較理解。</p><p>至於它的應用（例如建立一些資料管理的 dapp、分散式社群媒體的儲存等等) 與跟 Filecoin（獎勵大家貢獻儲存空間的幣）互動，去結合區塊鏈經濟模型與 IPFS 儲存協議的部分，也又是其他的待研究題目了。</p><p>已經有許多人在開發 IPFS 相關應用，可以參考以下清單：</p><ul><li><a href="https://docs.ipfs.io/concepts/usage-ideas-examples/">Usage ideas &amp; examples</a></li><li><a href="https://github.com/ipfs/awesome-ipfs">ipfs/awesome-ipfs</a></li></ul><h3>IPFS Reference</h3><ul><li><a href="https://docs.ipfs.io/">IPFS Documentation | IPFS Docs</a></li><li><a href="https://github.com/ipfs/go-ipfs">ipfs/go-ipfs</a></li><li><a href="https://blockcast.it/2019/10/21/mica-research-1-min-intro-of-ipfs/">【MICA RESERACH】一分鐘了解星際檔案系統 IPFS 原理與應用 - 區塊客</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10209569">開發 Dapp - 將 DApp 發佈到 IPFS (Day28) - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://flyingzumwalt.gitbooks.io/decentralized-web-primer/content/files-on-ipfs/lessons/add-and-retrieve-file-content.html">Lesson: Add Content to IPFS and Retrieve It</a></li><li><a href="https://medium.com/pinata/ethereum-and-ipfs-e816e12a3c59">Ethereum and IPFS</a></li><li><a href="https://hackernoon.com/understanding-ipfs-in-depth-3-6-what-is-interplanetary-naming-system-ipns-9aca71e4c13b">Understanding IPFS in Depth(3/6): What is InterPlanetary Naming System(IPNS)? | Hacker Noon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69a52abb954" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E8%A9%A6%E7%8E%A9-ipfs-a69a52abb954">試玩 IPFS</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[States and State Machines]]></title>
            <link>https://medium.com/wenchin-rolls-around/states-and-state-machines-8c9519018cd6?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c9519018cd6</guid>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 12:50:19 GMT</pubDate>
            <atom:updated>2020-12-23T14:03:57.384Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using state machines to define behaviors and state transitions — explained with dating apps</h4><h3>What’s a state?</h3><blockquote>In information technology and computer science, a system is described as <strong>stateful</strong> if it is designed to remember preceding events or user interactions; the remembered information is called the <a href="https://en.wikipedia.org/wiki/State_(computer_science)"><strong>state</strong></a> of the system.</blockquote><p>A system’s states are often defined by the aggregation of behaviors its users do. States are important because it’s a more systematic way of verifying whether certain behaviors at certain states are valid or not.</p><h4>States of a traffic light</h4><p>Consider a traffic light as an example. If it’s been green, drivers and passengers expect to see yellow — not red — next. When it turns yellow, they’d expect red and not green. So the states here are simple:</p><pre>Green -&gt; Yellow -&gt; Red<br>  ^                 |<br>  |_________________|</pre><p>Follow the arrows (aka the allowed transitions of states) and your traffic light’s good to go.</p><h4>States of the matches in dating apps</h4><p>Now let’s take a dating app as a more complicated example, imagine that we’re building an app for people to “match” online. Let’s say we have the algorithms ready and we need to start writing the logics behind the matches that pop up on our users’ apps.</p><p>Let’s define an entity <strong>match</strong> first to represent the match between two people. There are several states for a match we should take into consideration if we were to design it.</p><p>We need the states so that people won’t see unexpected behaviors such as a random, not-matched person showing up on the screen saying hello.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SqP9MGziRgscLzhcUgEzg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yogasdesign?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yogas Design</a> on <a href="https://unsplash.com/s/photos/tinder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>My thought process:</p><ol><li>First of all, a match has to be <strong>created</strong>, meaning a certain set of algorithms has to select two people ready for a match. Of course the algorithms need to make sure beforehand that they’re both up for a match, fit each other’s preferences, not banned, etc.</li><li>Then, this match could become either <strong>pending </strong>(waiting for another person’s swipe) or <strong>failed </strong>depending on the first user’s action. If the user swipes right (which means “I like you” in dating apps’ terms), the state jumps from <strong>created</strong> to <strong>pending</strong>. If the user swipes left (meaning “I don’t like you”), the state changes to <strong>failed</strong>.</li><li>Then if both people like each other, it goes from <strong>pending</strong> to <strong>matched</strong>.</li><li>Either of the person in a match could also “unmatch” a match, bringing the state to <strong>unmatched</strong>.</li><li>I think I got all the changes of states covered. But are these all? Hmm… isn’t there’s a paid feature called “rewind” which allows you to go back and swipe again? What should we do with this?</li></ol><p>How do we ensure that we’ve included all changes? If so how do we program it?</p><h3>What’s a state machine?</h3><blockquote>A methodology for modeling the behavior of an entity with an established lifecycle</blockquote><p>When building state-oriented systems, state machines are useful to help us better determine the complicated transitions and triggers.</p><h4>Finite state machines (FSM)</h4><blockquote>It is an <a href="https://en.wikipedia.org/wiki/Abstract_machine">abstract machine</a> that can be in exactly one of a finite number of <a href="https://en.wikipedia.org/wiki/State_(computer_science)"><em>states</em></a> at any given time. The FSM can change from one state to another in response to some <a href="https://en.wikipedia.org/wiki/Input_(computer_science)">inputs</a>; the change from one state to another is called a <strong>transition</strong>. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition.</blockquote><p>Let’s carry on with our dating app example. If we create a<strong> state diagram</strong> from the logics behind a <strong>match</strong>, it looks somewhat like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*2_eNcTH_I2R1Gc3FuYwIjA.png" /></figure><p><em>* Different methods can be taken by different users involved: either of the matched customers, or the dating app (platform builder / company).</em></p><p>It has a finite number of states, modeling all behaviors within a match’s lifecycle. To build a state machine, we just have to follow the lines and see how the entity responds to various behaviors.</p><h3>Why should I use a state machine?</h3><p>Okay now I know that the state diagram is really helpful, yet still why should I use a state machine when I’m writing my code?</p><p>From the same example, let’s take a look at some simplified code <strong>before</strong> and <strong>after</strong> a state machine’s involved.</p><h4>Before using a state machine</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aa8f1712a9a993f01e9756bd6a81b37/href">https://medium.com/media/2aa8f1712a9a993f01e9756bd6a81b37/href</a></iframe><p>You can spot a lot of if/else statements.</p><h4>After using a state machine</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a98b7aa8a3006dd80a58429a7daa4d8/href">https://medium.com/media/7a98b7aa8a3006dd80a58429a7daa4d8/href</a></iframe><p>Let the ChangeState method take care of state transitions using StateTransition type. All other methods can now focus on the logics of handling the match.</p><h4>What more can I do?</h4><p>Just to name a few:</p><ul><li>For now we assume that the “Rewind” methods are good enough for frontend interfaces to call. A more delicate way of dealing with methods should be to check if the match is recorded — and if so, is it liked or disliked — and then decide which command to use. Instead of letting the UI make the judgement (and risk it being wrong), it’s more suggested that we handle it in the MatchEntity class.</li><li>If the state transitions get too complicated, try using a matrix with axis of current states and commands. The data in the matrix can be the updated states. This way the code becomes more readable.</li></ul><h4>Summary</h4><p>So why use a state machine? Because considering the state-changing events (aka the important behaviors of an entity), it better models a system. Mostly everything else can be solved with basic CRUD methods. Also it makes your code more readable and maintainable.</p><p>When it comes to building APIs, don’t design them only based on the requests product managers make. Design APIs (at least minimum APIs) for your entity with the critical behaviors and transitions — states — in mind.</p><h3>Reference</h3><ul><li><a href="https://rclayton.silvrback.com/use-state-machines">Richard Clayton - Use State Machines!</a></li><li><a href="https://en.wikipedia.org/wiki/Finite-state_machine">Finite-state machine - Wikipedia</a></li><li><a href="https://stackoverflow.com/questions/5923767/simple-state-machine-example-in-c">Simple state machine example in C#?</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Fwenchin77%2Fbutton%2F&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fwenchin77&amp;image=https%3A%2F%2Fstatic.like.co%2Flikecoin_de-portrait.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="485" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href">https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9519018cd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/states-and-state-machines-8c9519018cd6">States and State Machines</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[與架構師對話：OOP 介面設計]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E8%88%87%E6%9E%B6%E6%A7%8B%E5%B8%AB%E5%B0%8D%E8%A9%B1-oop-%E4%BB%8B%E9%9D%A2%E8%A8%AD%E8%A8%88-ae5037f73d0b?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ae5037f73d0b</guid>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[程式設計]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 15:21:44 GMT</pubDate>
            <atom:updated>2020-11-29T15:42:52.728Z</atom:updated>
            <content:encoded><![CDATA[<h4>寫程式前先釐清每個物件的「我是誰？」和「我在哪裡？」</h4><p>最近架構師主管出了個作業給我們：<a href="https://zh.wikipedia.org/wiki/%E5%BA%B7%E5%A8%81%E7%94%9F%E5%91%BD%E6%B8%B8%E6%88%8F">康威生命遊戲</a>（Conway’s Game of Life），要用這個經典題目讓我們練習 OOP 介面 (interface) 的設計理念。本文記錄我跟他聊生命遊戲程式設計的對話過程。</p><p>他出作業的理由是：</p><blockquote>OOP 很強調 interface，而良好的 interface 是開出良好的 API 的基礎。看過太多用了先進開發工具與框架的工程師，卻設計出很糟糕的 API 有感。</blockquote><p>舉例來說：看到一個題目你會定義哪些類別？你定義的類別各自的職責是什麼？如何表達各物件間的關聯？這個任務適合由這個類別的物件來做嗎？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y53UAAFcsy64kIe2lG9c3Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@poemacollective?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Marisa Morton</a> on <a href="https://unsplash.com/s/photos/board?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>遊戲都有規則，我們馬上來看看這個遊戲怎麼玩。</p><h3>生命遊戲怎麼玩</h3><blockquote><strong>康威生命遊戲</strong>，又稱<strong>康威生命棋</strong>，是英國數學家<a href="https://zh.wikipedia.org/wiki/%E8%A9%B9%C2%B7%E4%BD%95%E9%A0%93%C2%B7%E5%BA%B7%E5%A8%81">約翰·何頓·康威</a>在 1970 年發明的<a href="https://zh.wikipedia.org/wiki/%E7%B4%B0%E8%83%9E%E8%87%AA%E5%8B%95%E6%A9%9F">細胞自動機</a>。</blockquote><p>簡而言之，你可以想像有個棋盤（或是一片稿紙、或是一塊塊綠豆糕），在它的每一格都放入細胞，可能是活細胞或死細胞。細胞會因為一些條件在一段時間後生長或死亡，你在放入細胞後就可以站在旁邊開始觀察一段時間並計算整個過程。</p><p>像這樣（黑色是活細胞、白色是死細胞）：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*58mhQd9CqVQv8wfq.gif" /><figcaption><a href="https://zh.wikipedia.org/wiki/%E5%BA%B7%E5%A8%81%E7%94%9F%E5%91%BD%E6%B8%B8%E6%88%8F">維基百科</a>：康威生命遊戲中的一種可持續繁殖模式「<a href="https://zh.wikipedia.org/w/index.php?title=%E6%AF%94%E5%B0%94%C2%B7%E9%AB%98%E6%96%AF%E5%B8%95&amp;action=edit&amp;redlink=1">高斯帕</a>機槍」</figcaption></figure><p>至於細胞變化的規則是什麼？（以下引用自<a href="https://zh.wikipedia.org/wiki/%E5%BA%B7%E5%A8%81%E7%94%9F%E5%91%BD%E6%B8%B8%E6%88%8F">維基百科</a>）</p><ul><li>每個細胞有兩種狀態 — 存活或死亡，每個細胞與以自身為中心的周圍八格細胞產生互動</li><li>當前細胞為存活狀態時，當周圍的存活細胞低於 2 個時（不包含 2 個），該細胞變成死亡狀態。（模擬生命數量稀少）</li><li>當前細胞為存活狀態時，當周圍有 2 個或 3 個存活細胞時，該細胞保持原樣。</li><li>當前細胞為存活狀態時，當周圍有超過 3 個存活細胞時，該細胞變成死亡狀態。（模擬生命數量過多）</li><li>當前細胞為死亡狀態時，當周圍有 3 個存活細胞時，該細胞變成存活狀態。（模擬繁殖）</li><li>可以把最初的細胞結構定義為種子，當所有在種子中的細胞<strong>同時</strong>被以上規則處理後，可以得到第一代細胞圖。按規則繼續處理當前的細胞圖，可以得到下一代的細胞圖，周而復始。</li></ul><h3>為何要用 OOP 玩這個遊戲</h3><p>用 OOP 版本的來寫生命遊戲的目的是：除符合已定義的規則可以執行無誤以外，經過正確的抽象化設計，可應付後續種種擴充的需求（比如說有病毒生長環境差一點還是可以成長、比如有變種細胞生長速度不同等等）。</p><p>當我的 OOP 版本程式碼通過測試後，我興奮的 slack 我主管。</p><p>「嗨，我寫好生命遊戲 OOP 版本的這個 milestone 了，想跟你討論討論，請問何時方便約個會議呢？」</p><p>「現在或一個月前都可以 :)」</p><p>好呀，工作之餘作業寫太慢還是被嗆了。</p><h3>與架構師的對話</h3><h4>版本一</h4><p>到了會議室，他打開我的 class diagram 說：「解釋一下你設計了哪些類別、為什麼要這樣設計它們？」</p><p>我：「簡單，因為細胞是根據周為八個細胞變化狀態的，所以我定義了一個類別叫做『細胞』，還有一個類別『世界』，細胞有一個方法可以去跟世界問目前所有細胞狀態，然後再照規則更新自己的狀態。」</p><p>「這樣的設計可以跑沒錯，但身為一顆細胞，你覺得你拿得到所有細胞狀態，是一件合理的事嗎？」</p><p>「欸好像怪怪的，我思考一下。」</p><h4>版本二</h4><p>我：「更新了！現在我設計的細胞有個方法，可以去跟世界說我是誰、我在哪裡，我要找我的鄰居，世界會根據它是誰告訴它，也不會跟它說超過它附近最多八個細胞範圍之外的資訊，我覺得職責合理一些！」</p><p>「等等，你是一個細胞，你怎麼知道你的位置？」</p><p>「喔簡單，細胞一出生（被 new 的時候），就會內建它的位置資訊在屬性裡！」</p><p>「你想一下，細胞的屬性有這個資訊是應該的嗎？這樣好了，我問你，你現在怎麼知道你在哪裡？例如你的經緯度？」</p><p>「我可以查 Google Maps。」</p><p>「對啊，所以你不太可能自己直接擁有自己的位置資訊。你一定是透過一個像是你說的 Google Maps 的工具輔助你取得你要的位置資訊，而這個工具可能也只允許你看到自己該看到的內容。因為知道自己位置跟周圍有誰不會是你自己的職責。」</p><p>「有道理！我靈感來了，讓我再改給你下一版。」</p><h4>版本三</h4><p>我：「經過上次討論，現在我調整成會讓細胞在被創造的時候，獲得一個叫做 GoogleMaps 的物件，只有透過這個，細胞才能『知道』我是誰、我在哪裡，而只取得自己的位置、鄰居資訊。」</p><p>「所以為了符合需求，你可能會去定義一些物件，那些物件不會那麼的直覺，但 OOP 就是要你運用抽象一點的思維層次。」</p><p>「對，我就是一開始直接用了最簡單粗暴的想法，沒有想到可以多定義別的物件。」</p><p>「因為你出動了上帝視角呀！很多工程師習慣遇到問題就開個上帝視角，讓大家都能拿取任何資訊，這樣程式可能可以跑、測項都能過，但是一旦邏輯開始複雜起來，需要擴充的時候（比如說有病毒生長環境差一點還是可以成長、比如有變種細胞生長速度不同等等），這樣的設計就會開始出事。而且真正在開發的時候，往往設計早就上線了，要調整基本架構會加倍辛苦，所以我才要你們練習在一開始就把設計弄對，而這個就是要透過 OOP 介面 (interface) 的設計來練習。」</p><p>「我以後努力記得不要扮演上帝。」</p><p>「拿到題目開始思考，你要定義什麼物件，怎麼處理它們誰可以做什麼，是非常關鍵的事。」</p><p>「但設計沒有一個標準答案吧？」</p><p>「是，可能大家定義的物件都不同，但只要職責符合，有精準表達需求，就可以是個及格的設計。」</p><p>「那為什麼 XXX （組內資深工程師）他們的設計都能一次到位？」</p><p>「因為你還需要練習呀！有了設計的經驗思考就會精準許多。練習的時候要不斷挑戰自己的介面設計邏輯，比如你去發想：在商業邏輯的合理範圍內，需求加了這個會怎樣、加了那個會怎樣、某部分設計需要交付不同人一起來寫會怎樣等等，實際寫看看，你可能就發現本來的設計出了問題、需要調整。生命遊戲這個經典題目就是一個很好的練習。」</p><p>「好我努力追你題目的 milestone 們。」</p><p>「下一個 milestone 細胞生長速度不一，就要考慮進去之前避開的時序問題啦，有時間可以趕快寫一下了。」</p><p>「好啦，這次一定不會拖一個月。」</p><h3>為什麼寫了這篇</h3><p>本來以為輕鬆愉悅的題目，越寫越發現我對介面設計的掌握度比自己想像的低，但偏偏這又是 OOP 超級基本功，也在跟主管、同事討論中獲得很多啟發，所以用這篇做個紀錄。但這裡純粹聊概念和思考過程，還沒有程式碼（畢竟要給大家一起挑戰的空間？而且我的設計不是典範型的設計。）如果之後有機會更完整寫好主管的題目（一 milestone 比一 milestone 高…）、看過不同的設計，再來寫一篇可能有程式碼的續集。</p><p>最後，身為 OOP 新手仍須很多很多的努力練習，歡迎多多交流、指教、分享與討論自己的設計，我會十分感激！</p><h3>如果你想寫看看</h3><p>單純只看演算法的話，可以去 <a href="https://leetcode.com/problems/game-of-life/">LeetCode #289</a> 寫看看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5037f73d0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E8%88%87%E6%9E%B6%E6%A7%8B%E5%B8%AB%E5%B0%8D%E8%A9%B1-oop-%E4%BB%8B%E9%9D%A2%E8%A8%AD%E8%A8%88-ae5037f73d0b">與架構師對話：OOP 介面設計</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HSTS 的坑]]></title>
            <link>https://medium.com/wenchin-rolls-around/hsts-%E7%9A%84%E5%9D%91-d05b7c023e7c?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d05b7c023e7c</guid>
            <category><![CDATA[hsts]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[程式學習]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sat, 31 Oct 2020 02:55:25 GMT</pubDate>
            <atom:updated>2020-10-31T06:15:48.576Z</atom:updated>
            <content:encoded><![CDATA[<p>最近寫 PoC 在打 API 取得資料、瀏覽器 set-cookie 的時候，遇到一點問題：用本地透過 https 打都沒事，但用 docker 改成用 http 打就失敗了。</p><p>跟同事追了整整半天 ASP.NET core 的 cookies, same-site, secure policy 設定，最後才發現問題根源完全不是這些，而是瀏覽器的快取跟 HSTS 設定，於是想寫篇筆記做個紀錄。</p><h3>問題</h3><p>情境：用 dotnet webapp 一個專案中的登入頁 (/Signin)，呼叫 HttpContext.SignInAsync，用 CookieAuthenticationDefaults 把登入成功拿到的資料（用戶名字、ID）塞到 cookies，轉址到會員資料頁 (/Member)。</p><pre>var claims = new List&lt;Claim&gt;<br>{<br>    new Claim(ClaimTypes.Name, name),<br>    new Claim(&quot;Id&quot;, user.Id.ToString())<br>};<br>var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);<br>await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));</pre><p>環境 1：在本地用 https://localhost:5001 打登入 API</p><p>環境 2：docker-compose 在 container 用 http://localhost:5000 打登入 API</p><p>問題：環境 1 成功、環境 2 拿到資料但無法成功放 cookies &amp; 轉址</p><h3>環境 1: localhost 用 https 打 API</h3><p>Request 打得通：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rUf0U55OojH0X3dP4wnSw.png" /></figure><p>Cookies 進得去：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EomXurc1_7cBeHqEb8nH6g.png" /></figure><h3>環境 2: docker-compose 用 http 打 API</h3><p>Request 打得通，但在瀏覽器的 set-cookie 最後有個驚嘆號，內容是：</p><blockquote><em>This set-cookie was not sent over secure connection and would have overwritten a cookie with the Secure attribute.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ml14nF6rVkQiXmj0q73ZA.png" /></figure><p>Cookies 進不去：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxeNaIrBJ8rqrdMm2kyo0Q.png" /></figure><h3>問題原因</h3><p>跟同事花很多時間研究 ASP.NET core 的 cookies, same-site, secure policy 設定，卻怎麼調都還是有這個問題。直到後來我異想天開幫 cookie 改個名字就成功在 docker 啟動，跟同事說這件事的時候，他說他看到一篇 <a href="https://stackoverflow.com/questions/37006238/asp-net-core-auth-cookie-not-being-set-in-google-chrome-when-running-in-dev">StackOverflow 問題</a>，說可能原因是瀏覽器快取造成的：</p><blockquote>While my localhost environment in VS worked fine and my user could be logged in this didn’t worked in the published environment for chrome.</blockquote><blockquote>This began when I was trying some self-signed-certificate stuff in IIS on my pre-production-environment by turining on https with configured bindings. And after that I went back to http.</blockquote><blockquote>What you could try in Chrome is this: Open the developer-tools goto tab <strong>Application</strong> and in the left pane choose <strong>Clear storage</strong>. Under the diagram on the right click <strong>Clear site data</strong> even if the usage shows 0 Bytes used. Do it anyway.</blockquote><blockquote>Finally I got my application with login features back.</blockquote><p>原來是因為 ASP.NET 初始一個 webapp 的時候自動會設定 UseHsts() ，所以當瀏覽器快取紀錄了本地的 https 打過，就不會容許用 http 再打同一支 API。</p><h3>解決方法</h3><p>如同上面那位 StackOverflow 的仁兄說的，按下 Clear site data （即便 storage 只有 0 byte），就可以清掉瀏覽器紀錄「曾經用 https 打過」的這件事。</p><p>（這邊隨便拿個網頁示意，應該要是 port 5000）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*6i7JzQNkze45ktNVrULtJQ.png" /></figure><h3>ASP.NET Core 關於 HSTS 的說明</h3><p>以下為官方文件：</p><h4>HTTP Strict Transport Security Protocol (HSTS)</h4><p>根據 <a href="https://www.owasp.org/index.php/About_The_Open_Web_Application_Security_Project">OWASP</a>， <a href="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html">HTTP Strict TRANSPORT Security (HSTS)</a> 是由 web 應用程式透過使用回應標頭所指定的選擇性加入安全性增強功能。 當 <a href="https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html#browser-support">支援 HSTS 的瀏覽器</a> 收到此標頭時：</p><ul><li>瀏覽器會儲存網域的設定，以防止透過 HTTP 傳送任何通訊。 瀏覽器會強制透過 HTTPS 進行所有通訊。</li><li>瀏覽器會防止使用者使用未受信任或不正確憑證。 瀏覽器會停用允許使用者暫時信任這類憑證的提示。</li></ul><p>由於 HSTS 是由用戶端強制執行，因此有一些限制：</p><ul><li>用戶端必須支援 HSTS。</li><li>HSTS 至少需要一個成功的 HTTPS 要求才能建立 HSTS 原則。</li><li>應用程式必須檢查每個 HTTP 要求，並重新導向或拒絕 HTTP 要求。</li></ul><p><a href="http://asp.net/">ASP.NET</a> Core 2.1 和更新版本會使用擴充方法來執行 HSTS UseHsts 。 UseHsts當應用程式不在<a href="https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/environments?view=aspnetcore-3.1">開發模式</a>時，會呼叫下列程式碼：</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    if (env.IsDevelopment())<br>    {<br>        app.UseDeveloperExceptionPage();<br>    }<br>    else<br>    {<br>        app.UseExceptionHandler(&quot;/Error&quot;);<br>        // The default HSTS value is 30 days. You may want to change this for production scenarios, see &lt;https://aka.ms/aspnetcore-hsts&gt;.        <br>        app.UseHsts();    <br>    }</pre><pre>    app.UseHttpsRedirection();<br>    app.UseStaticFiles();</pre><pre>    app.UseRouting();</pre><pre>    app.UseAuthorization();</pre><pre>    app.UseEndpoints(endpoints =&gt;<br>    {<br>        endpoints.MapRazorPages();<br>    });<br>}</pre><p>UseHsts 在開發中不建議使用，因為 HSTS 設定可由瀏覽器高度快取。 預設會 UseHsts 排除本機回送位址。</p><h3>Reference</h3><p><a href="https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&amp;tabs=netcore-cli">Enforce HTTPS in ASP.NET Core</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Fwenchin77%2Fbutton%2F&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fwenchin77&amp;image=https%3A%2F%2Fstatic.like.co%2Flikecoin_de-portrait.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="485" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href">https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d05b7c023e7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/hsts-%E7%9A%84%E5%9D%91-d05b7c023e7c">HSTS 的坑</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從 AppWorks School 轉職軟體工程師之路]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E5%BE%9E-appworks-school-%E8%BD%89%E8%81%B7%E8%BB%9F%E9%AB%94%E5%B7%A5%E7%A8%8B%E5%B8%AB%E4%B9%8B%E8%B7%AF-fa2c7df1a3eb?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa2c7df1a3eb</guid>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[程式設計]]></category>
            <category><![CDATA[軟體工程師]]></category>
            <category><![CDATA[appworks-school]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 15:23:49 GMT</pubDate>
            <atom:updated>2020-11-01T10:19:45.442Z</atom:updated>
            <content:encoded><![CDATA[<h4>透過培訓轉職後端工程師的心得</h4><p>因為最近又到了 <a href="https://school.appworks.tw/">AppWorks School</a> 的申請季節，身邊很多親朋好友在詢問我這個軟體培訓計畫 (coding bootcamp) 的種種，於是希望透過本文分享心路歷程給非本科系、也想轉職成為工程師的人們。官網有的內容不做過多贅述，這邊整理關於 AppWorks School 常常有人問我的問題、以及分享我個人的體驗。</p><p><em>* Disclaimer: 本文為非官方的個人心得</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUv3yOK8z9TbG8Dz_gHwXw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@seanlimm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sean Lim</a> on <a href="https://unsplash.com/s/photos/programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>AppWorks School 是什麼？</h3><blockquote>Code Your Future</blockquote><blockquote>遠距學習 4 週 + 駐點集訓 16 週，成為軟體工程師</blockquote><p>AppWorks School 是個「集結業界實務所需，精心設計的訓練課程」，目標就是透過它的培訓，你可以<strong>成為一位軟體工程師</strong>。</p><h3>我在 AppWorks School 花多少時間？</h3><p>AppWorks School 要求連續 16 週、每週約 70–75 小時的學習量。表訂每週一到五 9:00–18:00，但事實上，我待的時間大約是週一到週日 9:00–22:00，回家有時還會寫專案 / 學習到更晚。</p><h3>為什麼要遠距一個月？</h3><p>AppWorks School 校長第一天就說，程式學習一開始很好入門，所以坊間很多程式 101、從 0 到 1、「X 天寫出一個 app」 之類的課程，然而到了一定的知識量之後，你就會遇到一個黃金交叉：學習的難度提高、加上可以查得到資源減少，而開始卡關，這時如果沒有一個環境讓你可以專注且持續的學習、討論、試錯、反饋，你很可能就會（和大部分的學習者一樣）半途而廢。</p><p>所以 AppWorks School 讓你遠距一個月，先自己摸熟那些基本語法、再規定大家駐點集訓，跟導師和同學一起經歷那些卡關並突破。</p><h3>AppWorks School 如何訓練學員？</h3><blockquote>AppWorks School 重視實戰經驗，將透過專案的階段性目標，引導你循序漸進地自學，從實作各種功能到獨立自主完成專案，累積大量開發經驗並建立個人作品集，從中培養出「解決問題」與「自主學習」的能力。</blockquote><p>簡單來說：非常 hardcore。</p><p>我加入後發現這邊的訓練方式非常刺激。沒有老師站在台前說「跟著我這樣寫……」，反而每天有個看不大懂的任務要解。</p><p>舉例來說，我們有天的任務是「去 AWS 架設一台 EC2，讓網站在上面跑」。</p><p>就這樣！你會期待他加一句「AWS 是 Amazon 的雲端服務，你要用的 EC2 是一台虛擬伺服器，你可能要用 ssh 當鑰匙從本地連接它，才能從 command line 操控那台機器」，但沒有！沒任何別的提示，全部都得自己 Google 或者發問（問得太爛還會被打回去自己 Google）。</p><p>這個訓練方法一開始非常痛苦，因為連自己在做什麼都不知道，一天到晚亂下指令、在幫自己跟自己解衝突。</p><p>但其實後來跟很多工程師朋友聊到，這正是公司 RD 團隊工作上會真正使用的方法！大多時候，老闆才不會手把手帶你（除非你特別可愛而且他碰巧很閒），反而會是丟一個任務目標，要你去想辦法做出來。</p><p>這也是工程師的存在目的呀：解決問題。</p><p>這時候你就會發現<strong>學會問問題、</strong>跟<strong>下精準的 Google search 關鍵字</strong>就很重要。</p><p>後來有次跟 AppWorks School 老師聊教學方式的時候，他說：「很多資質不錯的學生適合的教法不是手把手一行一行教他們寫，反而是丟問題給他們自己去找解決方式，因為這個方式他們會學到最多。而事實上能力越好的學生越值得被這樣對待。」</p><p>這就是 AppWorks School 的訓練方法。就是因為知道程式的東西千變萬化，老師們只會在我們走火入魔的時候給點提示，要訓練我們解決問題的能力，而不是去死記某些問題的解答。</p><h3>我下班自學就好、幹嘛去 AppWorks School？</h3><p>有些東西明顯就是你自學得不到的：</p><ul><li>協作專案經驗</li><li>技術專題討論</li><li>企業參訪</li><li>就業媒合</li></ul><p>除此之外，我覺得最重要的是，這邊給了你一個<strong>全力奮鬥的環境</strong>，給你種種挑戰讓你成長（而且是往正確的方向），並讓你在面對各種挑戰時，身旁有著和你一樣摸索的同學、與給你提示方向的導師。</p><p>跟世界上很多事情一樣，寫程式不是一蹴可幾、可以速成的，而是靠長期的累積，這時候你身旁的同學就是關鍵，好在 School 的朋友都很願意分享自己學到的知識、也充滿學習慾望，跟這種人相處會常常被挑戰，卻也永遠都在學習，所以總是特別舒服。</p><p>從「你 npm install 了嗎？」、「我從 promise 到 async / await 教你一次好了」、「欸 Leetcode 四月有個 30 day challenge，要不要寫寫？」、「中午來開演算法讀書會」、「我們幫彼此模擬面試一下」到「你快去跟老師講八卦，讓他教我們 socket IO」、「XX 在徵工程師，要不要幫你丟履歷？」很幸運有一群可以一同成長的朋友，這五個月如果沒有他們我覺得我應該很難一一完成這些挑戰。</p><h3>該用什麼心態開始學程式？</h3><p>校長在第一天就跟我們講解正確的學習心法：<strong>模仿 — 記憶 — 理解</strong>。</p><p>他說寫程式就像寶寶學說話，我們牙牙學語的時候不可能知道那些字句的意涵，只是單純的複製、複製、複製，說久了就會有記憶、有語感，等長大了才去一一理解並更靈活的運用句子。</p><p>所以在接觸程式一開始，就要像個寶寶，了解到「不求甚解」是可以被接受的，不然你會鑽到死胡同裡。</p><p>這代表一開始你會由官方文件、別人 repo、Stack Overflow 等等地方抄了一堆程式碼生硬的使用，知其然而不知其所以然。直到你累積了一定的「感覺」，你才會慢慢往「理解」那一步邁進。這一切也會透過不斷循環而越來越有學習效率。</p><p>例如說你應該先是用了 Node.js 的非同步語法很久，才去學 <a href="https://link.medium.com/YKNVdspCZ7">event loop 那些底層一點的觀念</a>。這樣你一開始不會覺得太生澀而放棄，而後來學習整個系統背景知識時也能有個 ah ha moment：「噢！原來以前 async await 這樣寫是因為它這樣設計的。」讓你更快融會貫通。</p><p>AppWorks School 的學習步調也是這樣安排的：先透過實作給個感覺、再以技術討論補充背景知識。</p><h3>軟體工程師在幹嘛？</h3><p>廢話不多說，我們直接請前 Mozilla 工程師現身說法：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHtjP0h_NCRI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHtjP0h_NCRI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHtjP0h_NCRI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c904cc46954f3530f117c3f116999d/href">https://medium.com/media/71c904cc46954f3530f117c3f116999d/href</a></iframe><h3>不確定我想不想當個工程師，這樣還可以去 AppWorks School 嗎？</h3><p>就跟當時我問前幾屆的學員朋友的時候，他跟我說的一樣：你要想清楚，確定你真的想走這條路再去，否則會很辛苦、而且青春有限，去 AppWorks School 的機會成本如果是你更想做的事，就不要去。</p><p>但如果你想好了，<strong>有強烈的動機想成為一個軟體工程師</strong>（基本上如果沒有你也很難申請上啦）和全程投入的意願，也可以接受男 / 女友抱怨你每天很晚回家、以及犧牲很多社交生活、沒有時間和力氣兼差……等等，那我非常建議你丟出申請書，跨出舒適圈、接受這個挑戰。</p><h3>我是誰？為什麼我要轉職？</h3><p>我大學是讀管理學院，在讀書的時候從來沒有寫過程式，而畢業後在電商做了三年行銷、資料分析、策略方面的業務。對自動化工作內容跟有效率的解決問題方式很有熱情，因此很想接觸程式。</p><p>在加入 AppWorks School 之前有參加過公司辦的程式教學課，也在 Udemy 斷斷續續購買線上課程來學習程式，自學約 3 到 6 個月，期間不斷撞牆（一是有問題無法問人、二是不知道學的東西的意義或應用、三是自己利用晚上跟週末學習的效率很差），才選擇離職並在 2019 年 11 月加入 AppWorks School。現任電商 SaaS 平台軟體工程師。</p><h3>加入 AppWorks School 成為軟體工程師</h3><p>上連結：</p><ul><li><a href="https://school.appworks.tw/">AppWorks School</a></li><li><a href="https://school.appworks.tw/admission/">入學申請</a></li><li><a href="https://school.appworks.tw/outcome/">培訓成果</a></li></ul><p>有什麼其他問題都歡迎討論喔！</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Fwenchin77%2Fbutton%2F&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fwenchin77&amp;image=https%3A%2F%2Fstatic.like.co%2Flikecoin_de-portrait.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="485" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href">https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2c7df1a3eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E5%BE%9E-appworks-school-%E8%BD%89%E8%81%B7%E8%BB%9F%E9%AB%94%E5%B7%A5%E7%A8%8B%E5%B8%AB%E4%B9%8B%E8%B7%AF-fa2c7df1a3eb">從 AppWorks School 轉職軟體工程師之路</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[設計模式—建造者模式 (Builder Design Pattern)]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E8%A8%AD%E8%A8%88%E6%A8%A1%E5%BC%8F-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F-builder-design-pattern-7c8eac7c9a7?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/7c8eac7c9a7</guid>
            <category><![CDATA[設計模式]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 14:35:45 GMT</pubDate>
            <atom:updated>2020-06-30T14:35:44.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>客製化種種零件以打造複雜物件</h4><h3>建造者模式在幹嘛？</h3><p>建造者 (Builder) 模式將物件的「建構」與「表示」分離，隱藏並封裝建構過程的細節。它讓我們可以將物件本身拆解成不同的元件，一步一步建造每一部分，最後產生出我們想要的複雜物件。</p><blockquote><strong>Builder</strong> is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.</blockquote><h3>為什麼要用建造者模式？</h3><p>要解決的問題為：</p><ol><li>拖太長的建構子 (telescoping constructor)</li><li>建構子內不需要的參數必須放 null</li></ol><p>以下我們先用一個蓋房子的例子，來觀察這些問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2TZ2xmsjWJRcMJsLDdRfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christopher Burns</a> on <a href="https://unsplash.com/s/photos/construction-workers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>蓋一間房子</h4><p>假設我要創造一個房子的物件，那最簡單粗暴的方法就是定義一個物件 House、賦予它房子該有的屬性 (property)：窗戶數、門數、房間數，並使用建構子 (constructor) 來帶入這些參數。</p><p>以 pseudocode 表示：</p><pre>House(doorNum, windowNum, roomNum)</pre><h4>蓋許多間不同的房子</h4><p>今天假設我想要創建不同的房子：有花園的房子、有泳池的房子、有車庫的房子等等呢？</p><p>簡單，我們都知道可以把 House 變成 base class，再讓其他子類別繼承它，打造不同的房子。</p><p>這時為了記錄這些房子多出來的功能，我的 House 物件的屬性就要擴增成：窗戶數、門數、房間數、有無花園、有無泳池、有無車庫。</p><pre>House(doorNum, windowNum, roomNum, hasGarden, hasPool, hasGarage)</pre><p>那假設我這個 House 物件要給更多房子用：有雕像的房子、有健身房的房子、有爐火的房子等等，那這物件的參數會拖得很長。這顯然不是一個好的解法。</p><pre>House(doorNum, windowNum, roomNum, hasGarden, hasPool, hasGarage, hasStatue, hasGym, hasFireStove)</pre><p>因為當我要創造一個房子時，我很難一目瞭然每個建構子代表的意義：</p><pre>new House(2, 4, 3, true, true, true, false, false, false)</pre><p>而且如果今天我可能有一系列的房子沒有爐火管線、也禁止蓋健身房，那可能對於這些房子我都要把某些參數設為 null，增加更多的混亂：</p><pre>new House(2, 4, 3, true, true, true, false, <strong>null</strong>, <strong>null</strong>)</pre><h4>Builder: 客製化蓋房子的種種零件</h4><p>建造者模式用一種 configuration 的方式，拆解每個元件建造的過程，避免有拖得很長的建構子，使建構的意圖清晰許多。</p><p>因此剛剛那些房子，實現建造者模式的程式碼可能會長得像這樣：</p><pre>HouseBuilder.SetDoorNum(2);            <br>HouseBuilder.SetWindowNum(4);            <br>HouseBuilder.SetRoomNum(3);        <br>HouseBuilder.SetHasGarden(true);<br>HouseBuilder.SetHasPool(true);       <br>...    <br>HouseBuilder.GetHouse();</pre><p>或是這樣：</p><pre>new HouseBuilder().SetDoorNum(2)<br>                  .SetWindowNum(4)<br>                  .SetRoomNum(3)<br>                  .SetHasGarden(true)<br>                  .SetHasPool(true)  <br>                  ...<br>                  .Build();</pre><p>以下我們用另一個例子詳細說明，並在 C# 實現這兩種方式。</p><h3>怎麼實現建造者模式？</h3><h4>開一間水上活動工作室</h4><p>假設今天你擁有 SUP、獨木舟、浮潛、衝浪……的器材和專業，打算開一個水上活動工作室，設計不同的活動來銷售。</p><p>藉由建造者模式，我們可以開始設計不同的課程。</p><p>使用建造者模式的方法有兩種：</p><h4>方式一：透<em>過 Client、Director、Builder 和 Product 形成的建造者模式</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*xAiM-17lirZ0h0aF.png" /><figcaption>Source: <a href="https://refactoring.guru/design-patterns/builder">Refactoring Guru — Design Patterns: Builder</a></figcaption></figure><p><strong>Builder</strong>: 創建抽象建造者 ITripBuilder，僅宣告打造水上活動行程的步驟，不實作這些方法</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b69678be5d82424fe20ee987db2254/href">https://medium.com/media/37b69678be5d82424fe20ee987db2254/href</a></iframe><p><strong>Concrete Builder</strong>: 建立實體建造者 KayakTripBuilder, SupTripBuilder，實現 ITripBuilder 的各式設定</p><p>這邊以 SupTripBuilder 舉例，我們暫且假設 SUP 行程的價格都是 $3,000、行程時間都是 5 小時……，僅有地點是變動的：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/717a4f20bdc6e1d6245843e617f82116/href">https://medium.com/media/717a4f20bdc6e1d6245843e617f82116/href</a></iframe><p><strong>Director</strong>: 建立 TripDirector，讓它呼叫 KayakTripBuilder, SupTripBuilder 以建立行程的各個部分，並宣告一套流程按順序 (從 SetSalesContext, SetDestination, SetPrice… 接下去) 來建造複雜物件</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba1578b4f3a9d4577259dbd257327ba/href">https://medium.com/media/bba1578b4f3a9d4577259dbd257327ba/href</a></iframe><p><strong>Product</strong>: 建立一個物件 Trip 收整行程內容</p><p>這邊簡化的用 List 紀錄行程內容的字串，並直接 yield return 這些內容：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fef3ef98b397718a9d3e32cae94833f/href">https://medium.com/media/4fef3ef98b397718a9d3e32cae94833f/href</a></iframe><p><strong>Client</strong>: 建構完以上物件，我們可以在Program.cs呼叫 TripDirector 開始打造行程</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11b0619d3f3682a81d9d211ea5672ed2/href">https://medium.com/media/11b0619d3f3682a81d9d211ea5672ed2/href</a></iframe><p>Console output:</p><pre>SUP 象鼻岩行程:<br>【7/1-8/31 SUP 行程 85 折】<br>地點: 深澳象鼻岩<br>每人價格: NTD 3000<br>困難度: 3/5<br>時間: 5<br>每團人數限制: 10 人<br>SUP 活動敘述: 立式槳板運動（英語：Stand Up Paddle, SUP)，也俗稱「槳板」， 是起源於夏威夷的一種運動，由衝浪與傳統的手划槳板（Paddleboard）結<br>合而成。活動器材係由槳板（類似大型衝浪板）加上一支高於身高的單槳所組成。運用於衝浪時又稱立式單槳衝浪（簡稱立槳衝浪），也可在湖泊及河流等水 <br>域，從事探索、激流及救生等多方面的活動。<br>---<br>SUP 龜山島行程:<br>【7/1-8/31 SUP 行程 85 折】<br>地點: 龜山島牛奶湖<br>每人價格: NTD 3000<br>困難度: 3/5<br>時間: 5<br>每團人數限制: 10 人<br>SUP 活動敘述: 立式槳板運動（英語：Stand Up Paddle, SUP)，也俗稱「槳板」， 是起源於夏威夷的一種運動，由衝浪與傳統的手划槳板（Paddleboard）結<br>合而成。活動器材係由槳板（類似大型衝浪板）加上一支高於身高的單槳所組成。運用於衝浪時又稱立式單槳衝浪（簡稱立槳衝浪），也可在湖泊及河流等水 <br>域，從事探索、激流及救生等多方面的活動。<br>---<br>獨木舟 東澳行程:<br>【7/1-8/31 SUP 行程 85 折】<br>地點: 東澳海蝕洞<br>每人價格: NTD 3000<br>困難度: 3/5<br>時間: 5<br>每團人數限制: 10 人<br>SUP 活動敘述: 立式槳板運動（英語：Stand Up Paddle, SUP)，也俗稱「槳板」， 是起源於夏威夷的一種運動，由衝浪與傳統的手划槳板（Paddleboard）結<br>合而成。活動器材係由槳板（類似大型衝浪板）加上一支高於身高的單槳所組成。運用於衝浪時又稱立式單槳衝浪（簡稱立槳衝浪），也可在湖泊及河流等水 <br>域，從事探索、激流及救生等多方面的活動。<br>---</pre><h4>方式二：透<em>過靜態內部類方式實現建造者模式</em></h4><p>上面的假設是 SUP 行程價格、困難度、時間……都相同，僅地點有差異，所以 TripDirector 的參數只有一個。</p><p>然而今天可能行程一多，針對同樣都是 SUP（或同樣都是獨木舟）的行程，不同地點我們希望也做不同價格、困難度、時間……的設定。</p><p>這時候用第二種實現方法，會更加的彈性。</p><blockquote>這種方式使用更加靈活，更符合定義。內部有複雜物件的預設實現，使用時可以根據使用者需求自由定義更改內容，並且無需改變具體的構造方式。就可以生產出不同複雜產品</blockquote><p>在我們的例子，就是讓 Trip 本身可以直接設定傳入的參數，並且每個 Builder 方法都回傳 this，以達到 chaining 的效果。</p><p><strong>Builder</strong>: 創建抽象建造者 ITripBuilder，僅宣告打造水上活動行程的步驟，注意回傳型別也都是 ITripBuilder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7ed46aa46481b71623a1bb0c78681fc/href">https://medium.com/media/b7ed46aa46481b71623a1bb0c78681fc/href</a></iframe><p><strong>Concrete Builder</strong>: 建立實體建造者 KayakTripBuilder, SupTripBuilder，實現 ITripBuilder 的方法</p><p>這邊以 SupTripBuilder舉例，我們把 SetDestination, SetPrice… 等步驟都交給 Trip 這個最後要完工的物件去進行：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4df2de1afc9e396e652febb5da7d7e4/href">https://medium.com/media/c4df2de1afc9e396e652febb5da7d7e4/href</a></iframe><p><strong>Product</strong>: 建立一個物件 Trip 收整行程內容</p><p>和第一個方法不同，這個方法直接在物件中做 SetDestination, SetPrice… 等步驟。最後一樣全部整理成字串丟到一個 List 裡面：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccabe695e75897c7abd1e5008a75cf0c/href">https://medium.com/media/ccabe695e75897c7abd1e5008a75cf0c/href</a></iframe><p><strong>Client</strong>: 建構完以上物件，我們可以在Program.cs呼叫 Builder 並用 chaining 的方式打造行程</p><p>用這個方法可以更彈性就是因為順序（先設定地點還先設定價格？）、屬性多寡（要不要這個行程暫不設定行銷內容跟活動敘述？）都可以直接在建造 Trip 時決定。並且因為 TripBuilder 的方法都是回傳該 TripBuilder (this)，所以可以一路 chain 下去：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ace7785773a8d3133ff4f493f10c1a/href">https://medium.com/media/97ace7785773a8d3133ff4f493f10c1a/href</a></iframe><p>Console output:</p><pre>Trip 1. SUP 象鼻岩行程<br>【7/1-8/31 SUP 行程 85 折】<br>地點: 深澳象鼻岩<br>每人價格: NTD 2000<br>困難度: 2/5<br>時間: 4 小時<br>每團人數限制: 15 人<br>SUP 活動敘述: 立式槳板運動（英語：Stand Up Paddle, SUP)，也俗稱「槳板」， 是起源於夏威夷的一種運動，由衝浪與傳統的手划槳板（Paddleboard）結<br>合而成。活動器材係由槳板（類似大型衝浪板）加上一支高於身高的單槳所組成。運用於衝浪時又稱立式單槳衝浪（簡稱立槳衝浪），也可在湖泊及河流等水 <br>域，從事探索、激流及救生等多方面的活動。<br>---<br>Trip 2. SUP 龜山島行程<br>【7/1-8/31 SUP 行程 85 折】<br>地點: 龜山島牛奶湖<br>每人價格: NTD 5000<br>困難度: 4/5<br>時間: 6 小時<br>每團人數限制: 10 人<br>SUP 活動敘述: 立式槳板運動（英語：Stand Up Paddle, SUP)，也俗稱「槳板」， 是起源於夏威夷的一種運動，由衝浪與傳統的手划槳板（Paddleboard）結<br>合而成。活動器材係由槳板（類似大型衝浪板）加上一支高於身高的單槳所組成。運用於衝浪時又稱立式單槳衝浪（簡稱立槳衝浪），也可在湖泊及河流等水 <br>域，從事探索、激流及救生等多方面的活動。<br>---<br>Trip 3. 獨木舟 小琉球行程<br>【獨木舟振興券優惠套餐 開跑囉】<br>地點: 小琉球<br>每人價格: NTD 3500<br>困難度: 2/5<br>時間: 5 小時<br>每團人數限制: 20 人<br>SUP 活動敘述: 獨木舟是一種用單根樹幹挖成的划艇，需要藉助槳驅動。獨木舟的優點在於由一根樹幹製成，製作簡單，不易有漏水，散架的風險。它可以說<br>是人類最古老的水域交通工具之一。<br>---<br>Trip 4. 獨木舟 東澳行程<br>【獨木舟振興券優惠套餐 開跑囉】<br>地點: 東澳海蝕洞<br>每人價格: NTD 1500<br>困難度: 3/5<br>時間: 4 小時<br>---<br>Trip 5. 獨木舟 龍洞行程<br>【獨木舟振興券優惠套餐 開跑囉】<br>地點: 龍洞<br>每人價格: NTD 1500<br>---</pre><h4>GitHub repo</h4><p><a href="https://github.com/wenchin77/design-pattern-builder">方式一：透過 Client、Director、Builder 和 Product 形成的建造者模式</a></p><p><a href="https://github.com/wenchin77/design-pattern-builder/tree/builder-ver2">方式二：透過靜態內部類方式實現建造者模式</a></p><h3>Reference</h3><ul><li><a href="https://refactoring.guru/design-patterns/builder">Builder</a></li><li><a href="https://www.jyt0532.com/2017/06/29/builder/">Design Pattern(10) - Builder</a></li><li><a href="https://www.itread01.com/content/1545052746.html#%E4%B8%89%E3%80%81%E5%B8%B8%E8%A7%81%E7%AC%AC%E4%B8%80%E7%A7%8D%E6%96%B9%E5%BC%8F">Java 設計模式--建造者模式（Builder Pattern）</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8eac7c9a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E8%A8%AD%E8%A8%88%E6%A8%A1%E5%BC%8F-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F-builder-design-pattern-7c8eac7c9a7">設計模式—建造者模式 (Builder Design Pattern)</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[設計模式—工廠與抽象工廠 (Factory & Abstract Factory Design Pattern)]]></title>
            <link>https://medium.com/wenchin-rolls-around/%E8%A8%AD%E8%A8%88%E6%A8%A1%E5%BC%8F-%E5%B7%A5%E5%BB%A0%E8%88%87%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%BB%A0-factory-abstract-factory-design-pattern-8c28d29cb3ac?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c28d29cb3ac</guid>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[程式學習]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[設計模式]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 07:48:08 GMT</pubDate>
            <atom:updated>2020-06-27T08:49:26.328Z</atom:updated>
            <content:encoded><![CDATA[<h4>透過烤麵包的例子練習 C# 工廠設計模式</h4><p>我的 mentor 丟給我 <a href="https://refactoring.guru/">Refactoring Guru</a> 的設計模式 (design pattern) 教學網站一陣子了，剛好連假回家看見我媽在揉麵團烤麵包，因此想借用烤麵包的例子，練習一下工廠方法 (Factory Method) 和抽象工廠方法 (Abstract Factory Method)。</p><p><em>GitHub Repo: </em><a href="https://github.com/wenchin77/design-pattern-factory/tree/master"><em>工廠方法 branch</em></a><em>、</em><a href="https://github.com/wenchin77/design-pattern-factory/tree/abstract-factory"><em>抽象工廠方法 branch</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_56oZ2kPRdUJcQNafTRBA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kiboka?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nadya Spetnitskaya</a> on <a href="https://medium.com/s/photos/bakery?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>來做麵包吧</h3><p>今天我們想設計一間麵包店，先不要太複雜，就專做一種麵包：吐司。</p><p>首先要設計一個製造吐司的東西，可能是機器、團隊等等，這邊先當作是台機器，我們叫它 ToastMaker：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21427e09273c181ea07f2f8677a04be1/href">https://medium.com/media/21427e09273c181ea07f2f8677a04be1/href</a></iframe><p>很簡單：讓這個吐司店有「生產吐司」的方法，回傳一個我們另外定義的 Toast 類別的物件。如果把 Toast 產出那段加工一下，可以針對 Toast 物件做些處理，讓它回傳不同的吐司（巧克力吐司、花生醬吐司等等），享受一下多型 (polymorphism) 的好處。</p><p>很快的我們會發現一個問題，今天假設我的麵包店想多樣化一些，覺得光賣吐司不夠，希望也推出另外一種麵包，例如蛋糕，那就不能用 Toast 這個類別的物件，也不能在 ToastMaker 做事。如果程式碼這樣寫要修改的時候會有點麻煩。</p><h3>收整麵包種類</h3><p>這時候我們可以收整各式麵包種類到 IBread 這個介面 (interface)：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5491c81ecd73bdf8d6b7aac8f554b6e9/href">https://medium.com/media/5491c81ecd73bdf8d6b7aac8f554b6e9/href</a></iframe><p>並且交由各種麵包（吐司、蛋糕……）自己去實作。這邊設計了吐司和蛋糕為例，蛋糕比吐司多了形狀這個屬性：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/702d4026e10d4d1d78394a0ce696bab0/href">https://medium.com/media/702d4026e10d4d1d78394a0ce696bab0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766b6f5a752a64a92ecdc4bc8b766c5c/href">https://medium.com/media/766b6f5a752a64a92ecdc4bc8b766c5c/href</a></iframe><h3>設計一個麵包工廠</h3><p>創造了各種麵包種類後，現在我們把「製作麵包」功能拉出來，交給一個「工廠」負責。想賣的各式各樣麵包這個工廠都應該要做得出來，所以設定回傳型別為 IBread。</p><p>這個「工廠」我們透過一個抽象類別 (abstract class) 建立，命名為 Bakery，它要做的事就是產出麵包：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6779550a476b608bc6e6f39861128516/href">https://medium.com/media/6779550a476b608bc6e6f39861128516/href</a></iframe><p>當我們界定這個方法後，各種麵包就可以各自用 override 實作 CreateBread 的方法。吐司交由 ToastFactory 繼承、蛋糕交由 CakeFactory 繼承：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04a0dffd4558a54a2f5aff4e7c728c3/href">https://medium.com/media/c04a0dffd4558a54a2f5aff4e7c728c3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f1e8c24c5c859264b7c148a524e22e/href">https://medium.com/media/b1f1e8c24c5c859264b7c148a524e22e/href</a></iframe><p>工廠模式把麵包的創造裡會依據不同麵包而變動的部分 CreateBread 分離出去，交給工廠處理，因此方法會回傳不同的型別。</p><p>工廠會丟出一個 IBread，也就是麵包的一種。所以如果今天我想改變麵包的創造過程，那我可以在工廠處理，並在工廠的實作 (ToastFactory, CakeFactory…) 呼叫 CreateBread 方法時結果會不同。意即我只會在乎拿到的事不是 IBread 的子類別 (Toast, Cake…)，而不會去管工廠怎麼創造出它的。</p><blockquote><strong>Factory Method</strong> is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.</blockquote><p>而拿到 IBread 之後，也可以藉由 switch… case 語法操作型別轉換，做不同的反映。容我直接在 Program 操作我們的麵包店並讓 console 顯示：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/491cc37952105d70c07e4d6b38588c75/href">https://medium.com/media/491cc37952105d70c07e4d6b38588c75/href</a></iframe><p>Console output:</p><pre>Let&#39;s make some bread!<br>Toast: Peanut butter toast<br>Toast: Chocolate toast<br>Cake: Cheesecake<br>* Cake&#39;s shape: square<br>Cake: Strawberry cake<br>* Cake&#39;s shape: round</pre><p>工廠的使用會讓整個設計彈性很多，ToastFactory 和 CakeFactory 都繼承自 Bakery (也可以想成 BreadFactory)，所以當我們需要吐司的時候，就從 ToastFactory 去 new 一個吐司；需要吐司的時候，就從 CakeFactory 去 new 一個蛋糕。</p><p>如果想要推出新的麵包，例如 Panini 好了，那我們也可以依樣畫葫蘆從 Bakery 實作一個 PaniniFactory，來生產帕尼尼。</p><p>Bakery 只是界定方法，但真正決定怎麼生產麵包的還是子類別們 (ToastFactory, CakeFactory…)。</p><h3>工廠設計模式的結構</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*q47HoUyHKR2vSAOW.png" /><figcaption>Source: <a href="https://refactoring.guru/design-patterns/factory-method">Refactoring Guru — Design Patterns: Factory Method</a></figcaption></figure><ol><li>Product: 收整各種麵包物件的介面 <strong>IBread</strong></li><li>Concrete Product: 實作 IBread 的 <strong>Toast, Cake</strong> 等</li><li>Creator: 宣告 CreateBread 方法的 <strong>Bakery</strong></li><li>Concrete Creator: 實作 Bakery 裡面 CreateBread 方法的 <strong>ToastFactory 和 CakeFactory</strong>，回傳型別為 Concrete Product (Toast, Cake…)</li></ol><h3>如果我想用麵包的原料分工呢？</h3><p>今天如果我們麵包事業蒸蒸日上，想要開始專業分工、拆出不同的原料（麵粉、奶油、酵母粉等等）去做生產，那麼使用工廠方法就會異常複雜，因為可能因為產品定位或需求不同會有不同的原料：</p><ul><li>生產吐司用的麵粉工廠（高筋）</li><li>生產吐司用的奶油工廠（橄欖油）</li><li>生產蛋糕用的麵粉工廠（低筋）</li><li>生產蛋糕用的奶油工廠（無鹽奶油）</li><li>…</li></ul><p>如果每種麵包的蛋、鹽、糖、酵母粉等等也都要用不同的，那麼工廠方法就會讓系統非常複雜與難以維護。</p><p>此時我們會需要另一個維度的物件出現，去界定麵粉、奶油、酵母粉、蛋等等的實作，然後讓不同工廠使用不同原料物件，做出相異的麵包產品。</p><h3>抽象工廠設計模式</h3><p>這時抽象工廠 (Abstract Factory) 設計模式就派上用場了！</p><p>它是把工廠模式再抽象一層的設計模式。把本來生產麵包介面 IBread 拆成生產麵包的原料介面們，也就是不同種類麵粉、油、酵母粉等等的介面：IFlour, IOil, IPowder…，再到不同麵包的工廠 ToastFactory, CakeFactory… 當作該麵包要用的原料。</p><p>因為我們的假設是，製作麵包都要有麵粉、油、酵母粉…等等，只是類型和分量不同。例如蛋糕要用低筋麵粉、奶油，但吐司用的是高筋麵粉、橄欖油。而蛋糕可能起司蛋糕跟草莓蛋糕的麵粉和奶油份量佔比會不同。</p><h3>收整麵包原料種類</h3><p>現在我們把原料整理一下，交給不同的介面處理。這邊用麵粉跟油的介面舉例：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a112c5cde872f00e0d19251be26f85b/href">https://medium.com/media/4a112c5cde872f00e0d19251be26f85b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25778672362d28d90e197b80598e5f67/href">https://medium.com/media/25778672362d28d90e197b80598e5f67/href</a></iframe><p>再實作麵粉跟油的類別：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868a02360ed9f7bd70fab09929444a0f/href">https://medium.com/media/868a02360ed9f7bd70fab09929444a0f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dee9631bcee6ff8700515785d8a93d86/href">https://medium.com/media/dee9631bcee6ff8700515785d8a93d86/href</a></iframe><h3>建立抽象工廠、實作不同麵包工廠</h3><p>有了不同的原料類別，我們就能抽象工廠 Bakery (也可以想成 BreadFactory)，宣告 CreateFlour 跟 CreateOil 方法，讓實作的工廠去定義：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25c933003b59a0ca13d625edad01fc1/href">https://medium.com/media/d25c933003b59a0ca13d625edad01fc1/href</a></iframe><p>繼承這個抽象工廠後，我們就能開不同的麵包工廠：吐司工廠、蛋糕工廠……等等，去 override 剛剛宣告的方法：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b5b79880b8f0c3c2881e97c6611afa/href">https://medium.com/media/84b5b79880b8f0c3c2881e97c6611afa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a2392abbd513a4f74796ac1474a382/href">https://medium.com/media/e7a2392abbd513a4f74796ac1474a382/href</a></iframe><p>抽象工廠能拆開不同族群的物件，讓原料成為另一個維度。</p><blockquote><strong>Abstract Factory</strong> is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.</blockquote><p>下圖是另一個例子：把家具和風格拆開成不同維度去抽象化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*Qu3qa_A8T05ez4jz.png" /><figcaption>Source: <a href="https://refactoring.guru/design-patterns/abstract-factory">Refactoring Guru — Design Patterns: Abstract Factory Method</a></figcaption></figure><p>在 Client 丟進麵粉跟油的份量當作參數，就可以開始生產不同麵包了：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b48e3385a7875266e12d75d2ee803dc/href">https://medium.com/media/0b48e3385a7875266e12d75d2ee803dc/href</a></iframe><p>最後只要在 Program 呼叫 new Client().Main(); 即可。</p><p>Console output:</p><pre>Let&#39;s make some bread!<br>Cheesecake<br>---<br>Flour name: cake flour<br>Flour amount: 300<br>Oil name: butter<br>Oil amount: 100<br>---<br>Strawberry cake<br>---<br>Flour name: cake flour<br>Flour amount: 400<br>Oil name: butter<br>Oil amount: 150<br>---<br>Chocolate toast<br>---<br>Flour name: bread flour<br>Flour amount: 200<br>Oil name: olive oil<br>Oil amount: 50<br>---<br>Peanut butter toast<br>---<br>Flour name: bread flour<br>Flour amount: 200<br>Oil name: olive oil<br>Oil amount: 80<br>---</pre><h3>抽象工廠設計模式的結構</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GfQ1MfV2SltHL3kf.png" /><figcaption>Source: <a href="https://refactoring.guru/design-patterns/abstract-factory">Refactoring Guru — Design Patterns: Abstract Factory Method</a></figcaption></figure><ol><li>Product: 收整各種麵包原料物件的介面 <strong>IFlour, IOil…</strong></li><li>Concrete Product: 實作 IFlour, IOil 的 <strong>CakeFlour, BreadFlour, Butter, OliveOil… </strong>等</li><li>Abstract Factory: 宣告 CreateBread 方法的 <strong>Bakery</strong></li><li>Concrete Factory: 實作 Bakery 裡面 CreateBread 方法的 <strong>FlourFactory 和 OilFactory…</strong>，回傳型別為 Concrete Product (CakeFlour, BreadFlour, Butter, OliveOil…)</li><li>Client: 建立工廠並呼叫 CreateBread 方法，以得到 Product</li></ol><h3>Reference</h3><ul><li><a href="https://refactoring.guru/design-patterns/factory-method">Factory Method</a></li><li><a href="https://blog.techbridge.cc/2017/05/22/factory-method-and-abstract-factory/">設計模式 - 工廠方法及抽象工廠</a></li><li><a href="https://skyyen999.gitbooks.io/-study-design-pattern-in-java/content/factory.html">工廠模式 Factory Pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c28d29cb3ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/%E8%A8%AD%E8%A8%88%E6%A8%A1%E5%BC%8F-%E5%B7%A5%E5%BB%A0%E8%88%87%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%BB%A0-factory-abstract-factory-design-pattern-8c28d29cb3ac">設計模式—工廠與抽象工廠 (Factory &amp; Abstract Factory Design Pattern)</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[寫在做愛之前：認識子宮頸癌和 HPV]]></title>
            <link>https://medium.com/wenchin-rolls-around/hpv-f9c9bdab5bec?source=rss----ea7d514cd62c---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9c9bdab5bec</guid>
            <category><![CDATA[hpv]]></category>
            <category><![CDATA[性知識]]></category>
            <category><![CDATA[子宮頸癌]]></category>
            <category><![CDATA[科普心得]]></category>
            <category><![CDATA[子宮頸癌疫苗]]></category>
            <dc:creator><![CDATA[Wenchin]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 21:23:06 GMT</pubDate>
            <atom:updated>2021-08-27T03:01:22.600Z</atom:updated>
            <content:encoded><![CDATA[<h4>HPV 是什麼？子宮頸癌疫苗怎麼打？做愛為什麼要戴套？什麼時候要做子宮抹片？</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c35BVm4aknjLD6wAXqgsQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dainisgraveris?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dainis Graveris</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>上週跟朋友揪團去婦產科做抹片檢查和疫苗諮詢。在候診的時候，她說：「性需求好像每個女生都不大一樣。」</p><p>我說：「對啊，而且我覺得心理會影響生理。有性生活後就得好好檢查子宮，生為女生真的麻煩。到底為什麼人要有性慾？」</p><p>她說：「對啊！你不覺得如果人類沒有性慾、食慾這些基本生理需求，那會多出好多時間？」</p><p>我說：「還是我們等等進去問醫生這個問題？」</p><h3>為何而寫？</h3><p>當然，我們最後沒用這個哲學問題為難醫生。但在跟她、醫生還有許多友人聊天的過程中我發現，台灣人對很多極為基本的性知識大多似懂非懂，而且社會氣氛又偏向避諱公開談論性議題，導致很多時候疏忽了健康（不知道怎麼安全的做愛、不敢去做該做的檢查、不知道該檢查什麼……等等）。</p><p>長期忽略了預防和檢查，讓台灣每年約有 4,500 個子宮頸癌的新病例（含原位癌）發生，近 700 人死於這個癌症。</p><p>而定期篩檢和早期治療可以降低 60%-90% 子宮頸癌的發生率與死亡率。</p><p>於是乎我把和醫生諮詢過、以及衛生福利部說明的一些基本性知識整理在這裡。希望藉由這篇文章讓更多人理解各式各樣正確的性觀念和性健康、激發更多的討論。</p><h3>HPV 是啥？跟子宮頸癌有啥相關？</h3><p>HPV (Human Papillomavirus) 也就是人類乳突病毒（一種 DNA 病毒）。</p><p>你問我：「為什麼我們要認識這個病毒？」</p><blockquote>80% 有過性行為的女性一生中都曾感染 HPV。</blockquote><p>因為第一，80% 有過性行為的女生一生中都曾感染過它；第二，持續感染高危險型的 HPV 可能導致子宮頸癌。超過 99% 的子宮頸癌患者可檢驗出 HPV 病毒。</p><blockquote>人類乳突病毒(HPV)是一種DNA病毒，會感染人體的表皮與黏膜組織。它有一百多型，可以分為低危險型與高危險型，是男性及女性重要的性接觸傳染病原。HPV第16、18型是最常見的高危險人類乳突病毒，與子宮頸癌前病變、子宮頸癌以及男女外生殖器癌的發生有關，子宮頸癌有超過70%是由HPV第16、18型所引起的；低危險型HPV病毒(HPV第6、11型)是最常見的低危險人類乳突病毒，感染可能會引起生殖器疣(俗稱菜花)，致癌機率相對小。</blockquote><p>大部分的人因為免疫系統保護力夠，HPV 病毒並不會發展為癌症，多數時候甚至不會出現症狀，所以很多時候感染者並不會警覺到。</p><p>然而一旦持續感染高危險型 HPV，子宮頸就可能發生病變，最後導致癌化。</p><blockquote>女性子宮頸的細胞因感染高危險型人類乳突病毒 (HPV)，長期受到刺激而發生一連串的變化；正常健康的子宮頸細胞會因此而變得異常增生，而就有可能轉變為子宮頸癌細胞。</blockquote><p>你說：「等一下，所以 HPV 是透過什麼途徑找上我的子宮？」</p><p>看到這邊你應該也猜到了，性行為就是 HPV 最常見的傳染途徑。</p><blockquote>人類乳突病毒 (HPV) 主要經由性接觸傳染。在性行為過程中，透過接觸皮膚、黏膜或體液而感染。有時，外部生殖器接觸帶有 HPV 的物品，也可能造成 HPV。</blockquote><p>你驚呆了：「什麼？做愛竟然可能導致我得癌症？」</p><p>其實沒有這麼誇張。子宮頸癌一般需要幾年的時間才會形成，所以早期的預防和治療可以大幅度地降低得到子宮頸癌的機率。</p><blockquote>HPV感染者一般沒有明顯症狀，通常 9成的 HPV感染會在 1年內消失。部分感染者會出現菜花或其他生殖器病變，建議儘速就醫。</blockquote><h3>怎麼治好 HPV 病毒感染？</h3><p>現在沒有這治療 HPV 的藥。</p><p>但是發現它的存在並開始治療、防禦持續感染，是前往清空病毒的道路。</p><h3>怎麼預防 HPV 病毒感染？</h3><p>「好的，我現在比較理解這個病毒了，那請問我們怎麼避免被傳染呀？」</p><ol><li>戴套：性行為中全程使用保險套可以減少感染 HPV 的機會。</li><li>提升免疫力：維持良好生活作息以及充足營養，可維持較佳的免疫力，可使身體自動清除病毒，避免反覆受到感染。</li><li>打疫苗：子宮頸癌疫苗理論上也可預防許多型態的 HPV 感染。（但不建議懷孕期間或計畫疫苗注射期間懷孕者施打）</li></ol><h3>HPV 疫苗怎麼打？</h3><blockquote>目前全球共有3支疫苗上市，我國皆已核准上市，分別為二價疫苗及四價疫苗與九價疫苗。</blockquote><p>以下是三種疫苗的差異：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj128TGL0Q4iMgiqyYZFpQ.png" /><figcaption><a href="https://www.hpa.gov.tw/Pages/Detail.aspx?nodeid=1753&amp;pid=11885">HPV 疫苗衛教手冊 (民眾版) 第三版</a></figcaption></figure><p>衛福部國民健康署建議的施打對象：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*b0RyCW-NmcKQM3_m5VcN4A.jpeg" /><figcaption><a href="https://www.hpa.gov.tw/Pages/Detail.aspx?nodeid=1753&amp;pid=11885">HPV 疫苗衛教手冊 (民眾版) 第三版</a></figcaption></figure><p>「如果我還沒有過性行為，我可以打嗎？」</p><p>事實上，你是衛生機構最建議接種的人！因為疫苗對未發生性行為或未受到 HPV 感染者最為有效。</p><p>然而，有性行為的女生還是可以施打，保護自己於不同類型的 HPV 病毒感染。</p><h3>子宮抹片又是什麼？</h3><p>抹片就是醫生會採取子宮頸及陰道後壁的剝落細胞所做的檢查。</p><p>「那醫生會伸進去嗎？會不會痛？」</p><blockquote>子宮頸抹片檢查是一種簡單、快速且無痛的檢查方式，它能夠在診所或醫院實行。護士小姐會請妳將底褲解下躺在內診台上，醫師會用陰道擴張器來擴大陰道。檢查過程是以木製刮棒或子宮頸刷，將子宮頸四周和陰道後壁的細胞刮下。將細胞樣本抹在玻片上並迅速浸泡在固定液內固定，然後送至病理科進行細胞學檢查。</blockquote><p>「為什麼有過性行為的女生要做抹片？」</p><p>這個檢查能夠顯示出子宮頸有無感染、發炎、異常細胞或是癌症發生之可能。讓這些異常可以在發展為癌症之前被治療。</p><blockquote>子宮頸抹片可以早期發現子宮頸癌前病變或子宮頸癌。定期規律接受子宮頸抹片檢查，可降低 60–90%子宮頸癌發生率。若抹片報告異常並不代表一定有細胞病變或罹癌，應該接受進一步檢查(例如陰道鏡或子宮頸切片)才能確定病變程度。</blockquote><p>「如果已經停經或很久沒有性行為，我還要做抹片嗎？」</p><p>要喔！因為 HPV 病毒在體內如果沒有自行消除，還是可能幾年後演變為細胞病變，甚至子宮頸癌。</p><p>「那我要多常做抹片檢查呀？」</p><blockquote>目前國民健康署建議三十歲以上的婦女，至少每三年做一次子宮頸抹片檢查，若是未滿 30 歲但已有性行為三年以上的年輕女性，可考慮選擇自費檢查，以確保健康。</blockquote><p>「打過疫苗，我還得做抹片嗎？」</p><blockquote>近年研發之人類乳突病毒疫苗，理論上可以預防 60–70% HPV 感染。但因為疫苗尚未涵蓋所有病毒型別，所以定期接受子宮頸抹片檢查是必須的。</blockquote><h3>我是男生，我會感染 HPV 嗎？</h3><p>會喔！所以有任何症狀都應該盡速就醫。也很推薦男生打 HPV 疫苗，保護自己保護別人。</p><blockquote>事實上，HPV病毒的感染男女皆常見；它容易感染肛門及生殖區的皮膚及黏膜，引起外陰、肛門、陰莖與口咽部的鱗狀上皮細胞癌，而 HPV病毒大多數是透過性行為的接觸傳染疾病，人們自從有性行為開始，就有機會罹患 HPV病毒；根據統計結果顯示，HPV持續性感染者罹患子宮頸癌、外陰癌、直腸癌、陰莖癌的風險均會顯著增加。</blockquote><h3>好多資訊量！總結一下我該做些什麼？</h3><ol><li>戴保險套</li><li>戴保險套</li><li>戴保險套</li></ol><p>好啦我沒有要業配保險套的意思（還是有廠商想合作？）</p><p>以下是我覺得幾件<strong>簡單、效益很大、而且從今天就可以開始做</strong>的事：</p><ol><li>有性行為後定期做抹片檢查（順便找姐妹們一起去）</li><li>符合施打疫苗條件的話就去打疫苗（順便找兄弟姐妹們一起去）</li><li>性行為全程戴保險套（可能不用找姐妹們一起去）</li><li>男生女生有任何不舒服都馬上就醫，問婦產科醫生你想問的所有問題</li><li>多跟朋友討論正確的性知識（「正確」很重要，請選擇專案的醫生或知識源）、消弭因為無知而引起的害怕或逃避心態，千萬不要因為尷尬或害羞錯過獲得正確健康知識和檢查的機會！</li></ol><p>謝謝讀完以上資訊的人，我相信當越多人開始公開的討論子宮頸癌與 HPV，越能讓各個年齡層的女孩們照顧好子宮方面的健康。</p><blockquote>在台灣，子宮頸癌一直高居婦女癌症發生的第一位。然而子宮頸癌卻是婦女癌症中最容易早期發現的，子宮頸抹片檢查即是相當簡便、有效的方法。只要早期發現，早期治療，子宮頸癌的治癒率是很高的。</blockquote><p>讓我們期許一個每位女孩子宮都健康的台灣。</p><h3>Reference</h3><ul><li><a href="https://www.hpa.gov.tw/Pages/List.aspx?nodeid=1799">QA</a></li><li><a href="http://web.csh.org.tw/web/222010/?p=3066#:~:text=%E4%BA%8B%E5%AF%A6%E4%B8%8A%EF%BC%8CHPV%E7%97%85%E6%AF%92%E7%9A%84,%E9%A2%A8%E9%9A%AA%E5%9D%87%E6%9C%83%E9%A1%AF%E8%91%97%E5%A2%9E%E5%8A%A0%E3%80%82">【泌尿科】HPV人類乳突病毒 男性也要注意</a></li><li><a href="https://www.cch.org.tw/cchhec/knowledge_detail.aspx?oid=64">彰化基督教醫院 健康檢查中心</a></li><li><a href="https://www.hpa.gov.tw/Pages/Detail.aspx?nodeid=1753&amp;pid=11885">衛生福利部國民健康署</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Fwenchin77%2Fbutton%2F&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fwenchin77&amp;image=https%3A%2F%2Fstatic.like.co%2Flikecoin_de-portrait.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="485" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href">https://medium.com/media/08e28f347b3cc33ab55a5fc32454a1c3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c9bdab5bec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wenchin-rolls-around/hpv-f9c9bdab5bec">寫在做愛之前：認識子宮頸癌和 HPV</a> was originally published in <a href="https://medium.com/wenchin-rolls-around">Wenchin Rolls Around</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>