<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Design Pattern &#8211; Larry的午茶時光</title>
	<atom:link href="https://blog.yuyansoftware.com.tw/category/software-management/design-pattern/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.yuyansoftware.com.tw</link>
	<description></description>
	<lastBuildDate>Sat, 04 Jan 2025 15:15:05 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.3</generator>

<image>
	<url>https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/10/favicon-45x45.png</url>
	<title>Design Pattern &#8211; Larry的午茶時光</title>
	<link>https://blog.yuyansoftware.com.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>控制反轉 Inversion of Control (IoC)</title>
		<link>https://blog.yuyansoftware.com.tw/2013/12/inversion-of-control/</link>
					<comments>https://blog.yuyansoftware.com.tw/2013/12/inversion-of-control/#respond</comments>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Fri, 27 Dec 2013 13:12:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2013/12/27/inversion-of-control/</guid>

					<description><![CDATA[Inversion of Control 是區隔 library 與 framework 很重要的一個概念。M &#8230; ]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Inversion of Control 是區隔 library 與 framework 很重要的一個概念。<br>Martin Fowler 的文章<br><a rel="noreferrer noopener" aria-label=" (在新分頁中開啟)" href="http://martinfowler.com/bliki/InversionOfControl.html" target="_blank">http://martinfowler.com/bliki/InversionOfControl.html</a><br><a href="http://martinfowler.com/articles/injection.html" target="_blank" rel="noreferrer noopener" aria-label=" (在新分頁中開啟)">http://martinfowler.com/articles/injection.html</a></p>



<p class="wp-block-paragraph">以 design pattern 來說，Inversion of Control&nbsp;真正的精神是&nbsp;template method. 在 GoF 的 &lt;Design Patterns&gt; 中，template method 主要以繼承來達成。但是如果真正理解的話，用 composition 的方式一樣可以達成 template method.</p>



<p class="wp-block-paragraph">很多文章會把 Dependency Injection 與 Inversion of Control 擺在一起討論 (如上面 link)。主要是因為雖然兩者用意不同 (Dependency Injection 的目的是解除相依性，Inversion of Control 的目的是製造框架)，但常常產出的程式碼會相近，尤其是當&nbsp;Dependency Injection 被大量使用的時候。</p>



<p class="wp-block-paragraph">需注意的是，即使是少量的&nbsp;Dependency Injection, 一樣會伴隨小規模的&nbsp;Inversion of Control. 所以雖然兩者目的不同，但實為一體之兩面。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yuyansoftware.com.tw/2013/12/inversion-of-control/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Design Pattern 設計模式 (4): Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor</title>
		<link>https://blog.yuyansoftware.com.tw/2013/03/design-pattern-4/</link>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Sat, 30 Mar 2013 15:04:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2013/03/30/design-pattern-%e8%a8%ad%e8%a8%88%e6%a8%a1%e5%bc%8f%e5%ad%b8%e7%bf%92%e7%ad%86%e8%a8%98-%e5%9b%9b/</guid>

					<description><![CDATA[本系列目標在於依照 GoF 這本經典所介紹的 Design Patterns 做一個 review 與整理。本篇包含了 Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor。]]></description>
										<content:encoded><![CDATA[<p><u><span style="font-size: large;">Command Pattern</span></u><br />
<span style="font-size: large;">As you request an object to do some task, the object itself has no idea about the task before you tell it. The pattern makes the task (or command) into a class. The points about the pattern are:</span><br />
<span style="font-size: large;"># class <i>ConcreteCommand</i> inherits from class <i>Command</i>, and must implements</span><br />
<span style="font-size: large;">the <i>Execute</i> method.</span><br />
<span style="font-size: large;"># class <i>ConcreteCommand</i> has a reference of the receiving object. When the <i>Execute</i> method is called, the receiver acts as the <i>ConcreteCommand</i> designs.</span><br />
<span style="font-size: large;"># the creation and execution of a command can be at different time.</span><br />
<span style="font-size: large;"># the functionality of undo can be considered in the pattern.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Interpreter Pattern</span></u><br />
<span style="font-size: large;">Its general usage is to parse a string. When a sentence comes, a pattern parses it, and see if the sentence matches the pattern.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">In some level I think it is OK to think this pattern as the Composite Pattern. There are some things to note:</span><br />
<span style="font-size: large;"># the abstract and concrete classes should have the method <i>Interpret</i>.</span><br />
<span style="font-size: large;"># a general return data type for the <i>Interpret</i> method is bool. It returns true if the sentence matches the expression.</span><br />
<span style="font-size: large;"># theoretically, if you have lots of expression in your database, you will also need to create this number of expressions.</span><br />
<span style="font-size: large;"><br />
</span><br />
<a name="more"></a><span style="font-size: large;"><u><br />
</u><u>Iterator Pattern</u></span><br />
<span style="font-size: large;">Just think of the STL iterators, but the functionalities of a customized iterator can vary. I don&#39;t temporally address too much on this pattern.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Mediator Pattern</span></u><br />
<span style="font-size: large;">As the name, Mediator is to mediate the couplings between different objects. Especially when a object changes, the Mediator changes other objects. So basically, all the Concrete Colleagues should have the access to the Mediator, and the Mediator should have the access to all the Concrete Colleagues.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Memento Pattern</span></u><br />
<span style="font-size: large;">Doesn&#39;t have inheritance hierarchies. Instead, it emphasizes on the interaction of objects.</span><br />
<span style="font-size: large;">1. the client asks the Originator to create a Memento, which can belong to the client.</span><br />
<span style="font-size: large;">2. when the client needs the Originator to go back to a certain time, it calls <i>Originator::setMemento,&nbsp;</i>where the input is the Memento created before.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Observer Pattern</span></u><br />
<span style="font-size: large;">Participating classes: Subject and multiple Observers.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">As needed, the subject notifies all the observer to update. Compared to Mediator pattern, if regarding the mediator as observer, then the number of observers is only one.&nbsp;However, it can also take the mediator as subject. In this case, the observers become the role of&nbsp;Concrete Colleagues. But personally, in the view of semantics, regarding observer as a mediator is better.&nbsp;</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">Take OGRE <i>SampleContext</i> for example, <i>SampleContext</i> inherits from <i>OIS::KeyListener</i> and <i>OIS::MouseListener</i>, and implements the key and mouse event handling in it. In this case, <i>SampleContext</i> is an observer. In other words, it can be said to be an Observer Pattern that you register some observer classes to a subject class at the beginning, and the subject automatically updates the observers when necessary.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">State Pattern</span></u><br />
<span style="font-size: large;">Simply delegates some state-dependent work to the State class. So your module may have a State reference, which can be State1, State2, etc. There are two points needed to note:</span><br />
<span style="font-size: large;"># the State reference in your module can and should change.</span><br />
<span style="font-size: large;"># use State pattern to avoid a large if-else or switch-case chain.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Strategy Pattern</span></u><br />
<span style="font-size: large;">Personally I think it&#39;s just delegation. In a system, you might want to delegate a job to StrategyA, but in other cases, you might want delegate a job to StrategyB. Sometimes the pattern is used to switch the algorithms in your module.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Template Method</span></u><br />
<span style="font-size: large;">Template Method is a function in your class that defines the steps of certain work. However, the class doesn&#39;t &#8220;implement&#8221; the step functions (leave them empty), and the implementation is done by sub-classes. However, the implementation can also be delegated using the Strategy Pattern, so I think the emphasis of Template Method Pattern is to fix the steps in a template method.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">Visitor Pattern</span></u><br />
<span style="font-size: large;">I would say the pattern is also a kind of delegation. In this pattern you have a group of elements and visitors. Each element must implement the <i>accept</i> function, whose input is a visitor. Besides, each visitor must implement the <i>visitElementX</i> function (e.g., <i>visitElementA</i>, <i>visitElementB</i>, etc) depending on how many elements you have.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">In an element&#39;s <i>accept</i> function, the element has no idea of what to do, and just calls the visitor&#39;s <i>visitElementX</i> function. Note that the input of the<i> visitElementX</i> function is such element, so the code is something like: <i>visitor-&gt;visitElementA(this);</i> </span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">Let&#39;s see an example. There is a game that different people walk on a map, and events might arise when a person is at certain place. In this case, &#8220;place&#8221; is the element, and &#8220;person&#8221; is the visitor.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><span style="font-size: large;">References</span><br />
<span style="font-size: large;">[1] &#8220;Design Patterns&#8221;, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.</span></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Pattern 設計模式 (3): Facade, Flyweight, Proxy, Chain of Responsibility</title>
		<link>https://blog.yuyansoftware.com.tw/2013/03/design-pattern-3/</link>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Mon, 04 Mar 2013 14:28:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2013/03/04/design-pattern-%e8%a8%ad%e8%a8%88%e6%a8%a1%e5%bc%8f%e5%ad%b8%e7%bf%92%e7%ad%86%e8%a8%98-%e4%b8%89/</guid>

					<description><![CDATA[本系列目標在於依照 GoF 這本經典所介紹的 Design Patterns 做一個 review 與整理。本篇包含了 Facade, Flyweight, Proxy, Chain of Responsibility。]]></description>
										<content:encoded><![CDATA[<p><span style="font-size: large;">此篇文章會介紹 Facade, Flyweight, Proxy, and Chain of Responsibility patterns.</span><br />
<span style="font-size: large;"><br />
</span><u><span style="font-size: large;">1. Facade Pattern</span></u><br />
<span style="font-size: large;">Facade pattern 的使用時機基本上就是當你的模組有很多 sub-module 時, 提供一個簡單的介面供系統調用. 架構上就是用一個大 class (即是 facade) 將 sub-module 們包裹起來, 此 facade 通常要負責 sub-module 們的生成與毀滅. 另外要注意的是 facade 要有將 sub-modules 與系統 decouple 的責任. Facade pattern 就個人的意見來說並不算是所謂的 &#8220;Design Pattern&#8221;, Facade Pattern 的精神只是將 sub-modules 包裹起來, 提供系統一個簡單的介面, 在此不再贅述.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">2. Flyweight Pattern</span></u><br />
<span style="font-size: large;">使用時機: 當系統中不同 client 端可以共用 object 時, 以節省 memory cost.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">多個 client 跟一個 factory query objects. 當 query 同一 object 時, ClientA, ClientB 應拿到實體為同一個的 object. object 的生成與消滅應由此 factory 負責.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">另外[1]中提到</span><br />
<span style="font-size: large;"># UnsharedConcreteFlyweight 與 SharedConcreteFlyweight 的概念. UnsharedConcreteFlyweight 常常是 SharedConcreteFlyweight 的 aggregation.</span><br />
<span style="font-size: large;"># intrinsic/extrinsic state 的概念. SharedConcreteFlyweight 要有自己的 intrinsic state, 其是不隨 client 端的 context 改變的. 相對的, 調用 flyweight 時則須由外部傳 client context 進來, 即是 extrinsic state.</span><br />
<span style="font-size: large;"><br />
</span><u></u><br />
<a name="more"></a><span style="font-size: large;"><u><br />
</u><u>3. Proxy Pattern</u></span><br />
<span style="font-size: large;">使用時機: 當一 class 的多個 operation 工作內容需要更改時.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;">一 Proxy class 覆蓋多個或全部 Subject class 的函式, 此 Proxy 可以負責創造 Subject 或是只 keep reference. 制定架構規格時可以創造一 AbstractSubject, 令 Proxy 與 Subject 同時繼承之.</span><br />
<span style="font-size: large;"><br />
</span><span style="font-size: large;"><br />
</span><u><span style="font-size: large;">4. Chain of Responsibility</span></u><br />
<span style="font-size: large;">使用時機: 有任務是須要一個項目一個項目確認, 或是一關一關過時.</span><br />
<span style="font-size: large;"><br />
</span></p>
<p><span style="font-size: large;">References</span><br />
<span style="font-size: large;">[1] &#8220;Design Patterns&#8221;, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.</span></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Pattern 設計模式 (2): Adapter, Bridge, Composite, Decorator</title>
		<link>https://blog.yuyansoftware.com.tw/2013/02/design-pattern-2/</link>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Mon, 18 Feb 2013 15:08:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2013/02/18/design-pattern-%e8%a8%ad%e8%a8%88%e6%a8%a1%e5%bc%8f%e5%ad%b8%e7%bf%92%e7%ad%86%e8%a8%98-%e4%ba%8c/</guid>

					<description><![CDATA[本系列目標在於依照 GoF 這本經典所介紹的 Design Patterns 做一個 review 與整理。本篇包含了 Adapter, Bridge, Composite, Decorator。]]></description>
										<content:encoded><![CDATA[<p><span style="font-size: large;">本文會依序介紹 Adapter, Bridge, Composite, 與 Decorator patterns. 各自的內容會分別以使用時機, 架構, 實作相關(optional)來描述.</span><br><span style="font-size: large;"><br></span><u><span style="font-size: large;">1. Adapter Pattern</span></u><br><span style="font-size: large;">使用時機: 現有模組介面不完全 fit in 現有架構或未來架構規劃. 另一說法就是更改現有模組介面.</span></p>
<p><span style="font-size: large;">Adapter pattern 的參與 class 為 <i>Target</i>, <i>Adapter</i>, <i>Adaptee</i>. Client&nbsp;擁有或操作 <i>Target</i>, <i>Adapter</i>&nbsp;則負責將 <i>Adaptee</i> 的介面轉換成符合 <i>Target</i> 的介面. Adapter pattern 分為兩種架構: 多重繼承的架構為 class adapter, 另一種則為 object adapter. class adapter 同時繼承於 <i>Target</i> 與&nbsp;<i>Adaptee</i>, 由於是繼承關係, class adapter 較易更改 <i>Adaptee</i> 內部行為. 然而 object adapter 則是包含 (has or can access) <i>Adaptee</i>, 同時繼承於&nbsp;<i>Target</i>, 所以較強調 <i>Adaptee</i> 的封裝完整. [1] 中有補充 class adapter 無法處理有 sub-classes 的 <i>Adaptee</i> (adapt 其 sub-classes); 關於 object adapter 的是其可以擁有多個 <i>Adaptee</i>.</span><br><span style="font-size: large;"><br></span><span style="font-size: large;">另外 [1] 中提到利用 class adapter 的架構, <i>Adaptee</i> 與 <i>Target</i> 的角色可互換, 達到雙向 adapt 的功用.</span><br><span style="font-size: large;"><br></span><span style="font-size: large;">實作須知: class adapter 的做法基本上要 public 繼承 <i>Target</i>, private 繼承 <i>Adaptee</i>.</span></p>
<p><span style="font-size: large;"><br></span><u><span style="font-size: large;">2. Bridge Pattern</span></u><br><span style="font-size: large;">使用時機: 將 base class 的某些 method 拉出來由另一繼承樹實作.</span><br><span style="font-size: large;"><br></span><span style="font-size: large;">架構範例:</span></p>
<div style="clear: both; text-align: center;">&nbsp;</div>
<div style="clear: both; text-align: center;"><a style="margin-left: 1em; margin-right: 1em;" href="http://4.bp.blogspot.com/-PkdADo5V62k/UUklHovZHeI/AAAAAAAAAOA/A28wnHcgUCQ/s1600/Bridge_Pattern.png"><span style="font-size: large;"><img fetchpriority="high" decoding="async" src="https://4.bp.blogspot.com/-PkdADo5V62k/UUklHovZHeI/AAAAAAAAAOA/A28wnHcgUCQ/s640/Bridge_Pattern.png" width="640" height="243" border="0"></span></a></div>
<p><span style="font-size: large;"><br></span><u><span style="font-size: large;">3. Composite Pattern</span></u><br><span style="font-size: large;">使用時機: 待處理的物件們可以畫成 Composite-Leaf 樹狀圖.</span><br><span style="font-size: large;"><br></span><span style="font-size: large;">參與 class 為<i> Component</i>, <i>Composite</i> 與 <i>Leaf</i>. <i>Composite</i> 與 <i>Leaf</i> 皆繼承 <i>Component</i>, client 只調用 <i>Component</i> 的介面, 另外 <i>Composite</i> 中包含了多個 <i>Component</i> (可以是&nbsp;<i>Composite&nbsp;</i>或&nbsp;<i>Leaf&nbsp;</i>).</span></p>
<p><span style="font-size: large;"><br></span><u><span style="font-size: large;">4. Decorator Pattern</span></u><br><span style="font-size: large;">使用時機: 須要動態對一物件的某一功能做增強時.</span><br><span style="font-size: large;"><br></span><span style="font-size: large;">架構範例 (此 pattern 與 Composite Pattern 有幾分相似, 可以比較一下)</span></p>
<div style="clear: both; text-align: center;">&nbsp;</div>
<div style="clear: both; text-align: center;"><a style="margin-left: 1em; margin-right: 1em;" href="http://4.bp.blogspot.com/-YttP-2plGU8/UUkmfVuGU3I/AAAAAAAAAOQ/zph9-Ja138w/s1600/decorator.png"><span style="font-size: large;"><img decoding="async" src="https://4.bp.blogspot.com/-YttP-2plGU8/UUkmfVuGU3I/AAAAAAAAAOQ/zph9-Ja138w/s640/decorator.png" width="640" height="480" border="0"></span></a></div>


<p class="wp-block-paragraph">References<br>[1] &#8220;Design Patterns&#8221;, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Delegate (委託模式), and its difference in C++ and C#</title>
		<link>https://blog.yuyansoftware.com.tw/2013/01/delegation-c-plus-c-sharp/</link>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Sat, 19 Jan 2013 09:38:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2013/01/19/delegation-and-its-difference-in-c-and-c/</guid>

					<description><![CDATA[Delegate (委託模式) 的概念一直懂得不是很徹底，此篇試圖釐清一些委託的概念。 先了解委託的精神是什麼 &#8230; ]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Delegate (委託模式) 的概念一直懂得不是很徹底，此篇試圖釐清一些委託的概念。</p>



<p class="wp-block-paragraph">先了解委託的精神是什麼, from<br><a rel="noreferrer noopener" aria-label="http://en.wikipedia.org/wiki/Delegation_(programming) (在新分頁中開啟)" href="http://en.wikipedia.org/wiki/Delegation_(programming)" target="_blank">http://en.wikipedia.org/wiki/Delegation_(programming)</a></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>&#8220;delegation refers to one object relying upon another to provide a specified set of functionalities. In research, this is often referred to as consultation or as aggregation in modeling.&#8221;</p></blockquote>



<p class="wp-block-paragraph">另外委託的概念與 Design Pattern 中的 Observer pattern 有關，這部分讀者可以另外再去研讀。</p>



<p class="wp-block-paragraph">上網查詢了C++關於委託的文章，還是不能充分理解。以下會先介紹微軟官網 C# Delegation 的範例，接著試著將該範例以C++實現，看能否勾勒出C++關於委託的概念。</p>



<p class="wp-block-paragraph"><a href="http://msdn.microsoft.com/zh-tw/library/aa288459(v=vs.71).aspx" target="_blank" rel="noreferrer noopener" aria-label=" (在新分頁中開啟)">http://msdn.microsoft.com/zh-tw/library/aa288459(v=vs.71).aspx</a><br>在範例一中，</p>



<pre class="wp-block-code"><code>public delegate void ProcessBookDelegate(Book book);</code></pre>



<p class="wp-block-paragraph">宣告了委託型別，注意他不屬於任一 class, 在調用時</p>



<pre class="wp-block-code"><code>bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));</code></pre>



<p class="wp-block-paragraph">BookDB::ProcessPaperbackBooks 的 argument type 為 ProcessBookDelegate. 而 ProcessBookDelegate 的實作則依賴於 &#8220;new ProcessBookDelegate(PrintTitle)&#8221;, 也就是 PrintTitle. 注意 Test::PrintTitle 是 static function, 不然 compile 時會沒有其位置資訊。</p>



<p class="wp-block-paragraph">這樣的做法是要 run-time 決定 BookDB::ProcessPaperbackBooks 的行為，而且此行為會受BookDB 物件內容影響。範例一中還有一次委託：</p>



<pre class="wp-block-code"><code>bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));</code></pre>



<p class="wp-block-paragraph">這次是傳物件的 method 進 BookDB::ProcessPaperbackBooks.</p>



<p class="wp-block-paragraph">結論：Delegation (委託) 大致上可以說是從外部傳 static function 或 class method 進要委託工作的人。</p>



<p class="wp-block-paragraph">要委託工作的人 run-time 調用 delegate function (compile-time 要委託工作的人並不知道 delegate 是誰)，然後此 delegate function 會依照要委託工作的人的狀態工作。</p>



<p class="wp-block-paragraph">使用時機就如同上述範例一般：當要 run-time 決定要對底下所有物件 (ex: Book) 做不同處理時，可以用 Delegation.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Pattern 設計模式 (1): Abstract Factory, Factory Method, Singleton, Builder, Prototype</title>
		<link>https://blog.yuyansoftware.com.tw/2012/12/design-pattern-1/</link>
		
		<dc:creator><![CDATA[Larry]]></dc:creator>
		<pubDate>Sun, 09 Dec 2012 10:18:00 +0000</pubDate>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[軟體工程與管理]]></category>
		<guid isPermaLink="false">http://test234.yuyansoftware.com.tw/2012/12/09/design-pattern-%e8%a8%ad%e8%a8%88%e6%a8%a1%e5%bc%8f%e5%ad%b8%e7%bf%92%e7%ad%86%e8%a8%98-%e4%b8%80/</guid>

					<description><![CDATA[本系列目標在於依照 GoF 這本經典所介紹的 Design Patterns 做一個 review 與整理。本篇包含了 Abstract Factory, Factory Method, Singleton, Builder, Prototype。]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">本系列目標在於依照 [1] 這本經典所介紹的 Design Patterns 做一個 review 與整理。</p>



<p class="wp-block-paragraph">本文我想先討論 [1] chapter 1 中 <strong>code reuse</strong> 的概念，接下來整理 Abstract Factory，Factory Method，Singleton，Builder，Prototype patterns。</p>



<p class="wp-block-paragraph">在 [1] chapter 1 中 <strong>code reuse</strong> 主要分為三大類：Inheritance, Composition, Parameterized Types (Templates)。其中各自的優缺點是：</p>



<h4 class="wp-block-heading">1. Inheritance</h4>



<p class="wp-block-paragraph"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">優</mark>：繼承關係程式碼可讀性高，架構容易理解。<br>缺：繼承關係是在 compile-time 就決定，flexibility 低。<br>缺：sub-class 有權更動 super-class 內部資料與行為，打破封裝。反之，super-class 的更動也會影響 sub-class 的行為。</p>



<h4 class="wp-block-heading">2. Composition</h4>



<p class="wp-block-paragraph"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">優</mark>：可以在 run-time 再決定 composition objects，flexibility 高。<br><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">優</mark>：維持 composition objects 的封裝性。<br>缺：程式可讀性低。</p>



<h4 class="wp-block-heading">3. Templates</h4>



<p class="wp-block-paragraph">compile-time 定義。</p>



<p class="wp-block-paragraph">書中的意見是：Composition 是比 Inheritance 好的 <strong>reuse</strong> 技術，Templates 則提供了第三種選項。我個人認為：Inheritance 與 Composition 使用時機上並不同，有需要<strong>更動到 class 內部</strong>的要選用 Inheritance，無此需求的時候，當然就是選擇 Composition 了。</p>



<p class="wp-block-paragraph"><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">接著開始 5 個 design patterns 的討論。</mark></p>



<h4 class="wp-block-heading">1. Abstract Factory</h4>



<p class="wp-block-paragraph">首先以範例先描述 Abstract Factory。假設麥當勞的一號餐與二號餐會隨著夏季冬季作口味上的調整，則其模型可以如下：</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="512" height="283" src="https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Abstract_Factory.png" alt="Design Pattern 設計模式 Abstract Factory" class="wp-image-12671" srcset="https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Abstract_Factory.png 512w, https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Abstract_Factory-300x166.png 300w" sizes="(max-width: 512px) 70vw, 512px" /></figure>
</div>


<p class="wp-block-paragraph">以上例子可以勾勒出 Abstract Factory 的使用時機及好處：</p>



<ul class="wp-block-list">
<li>生產 product (一號餐二號餐) 的責任完全與系統無關，系統甚至不須知道目前是<strong>夏季一號餐</strong>還是<strong>冬季一號餐</strong>，系統只要照著一般一號餐的管理與使用方式即可。以程式語言來說，系統與 factory 和 product 實作完全沒相依性，是很好的設計。</li>



<li>系統中所需物件可以被分類。以此範例來說，我們總共有夏季一號餐、冬季一號餐、夏季二號餐、冬季二號餐。很直覺的想法就是把他們分為夏季一組、冬季一組。當系統 configure 成夏季時即產生夏季的餐點，當系統 configure 成冬季時即產生冬季的餐點。</li>
</ul>



<h4 class="wp-block-heading">Abstract Factory 實作須知：</h4>



<ul class="wp-block-list">
<li>concrete factory 應以 singleton 方式實作。</li>



<li>Abstract Factory 新增 product 可以改為用參數指定的方式。以上面範例來說，假如要新增夏季三號餐，當然<strong>夏季麥當勞廚房</strong>要改變，另外<strong>麥當勞廚房</strong>、<strong>冬季麥當勞廚房</strong>也要一起變動。所以另一種方式是，兩個 method <strong>生產一號餐</strong>與<strong>生產二號餐</strong>改為<strong>生產餐點(餐點號碼)</strong>，這樣對單一 concrete factory 的擴充性會方便許多。</li>
</ul>



<h4 class="wp-block-heading">2. Factory Method</h4>



<p class="wp-block-paragraph">首先以範例先描述 Factory Method。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="320" height="267" src="https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Factory_Method.png" alt="Design Pattern 設計模式 Factory Method" class="wp-image-12674" srcset="https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Factory_Method.png 320w, https://blog.yuyansoftware.com.tw/wp-content/uploads/2022/11/Factory_Method-300x250.png 300w" sizes="auto, (max-width: 320px) 70vw, 320px" /></figure>
</div>


<p class="wp-block-paragraph">顧名思義，Factory Method 著重在 <strong>creation function</strong> 這個 method。Super-class 有一個 creation function，依照需求利用 sub-class 對此 creation function 做轉型。在未來開發而言，Factory Method 支援 <strong>parallel class hierarchies</strong>，這是很值得參考的做法。</p>



<h4 class="wp-block-heading">Factory Method 實作須知：</h4>



<ul class="wp-block-list">
<li>同 Abstract Factory 第二項實作須知，參數化的 creation function 會有彈性很多。</li>



<li>使用 Factory Method 會容易產生過多的 sub-class (因為基本上它是與 product type 綁在一起)。此時 sub-class 可以以 template 的方式實作，理論上就會只有一個 template sub-class 了。</li>



<li>[1]中提到 naming conventions。很多 framework 甚至規定 Factory Method 的 function name，使開發者一看就知道是 Factory Method。很多人可能認為這是小東西，但我個人認為軟體開發程式的基礎建設一定要做好，將來才可以是可管理、可測試的專案。</li>
</ul>



<h4 class="wp-block-heading">3. Singleton</h4>



<p class="wp-block-paragraph">Singleton 的範例我想直接用 sample code 來描述。</p>



<pre class="wp-block-code"><code>class Singleton
{
public:
    static Singleton* getInstance( );
protected:
    Singleton( );
private:
    static Singleton* m_instance;
};

Singleton::m_instance = NULL;

Singleton* Singleton::getInstance( )
{
    if( m_instance == NULL )
    {
        m_instance  = new Singleton;
    }
    return m_instance;
}</code></pre>



<p class="wp-block-paragraph">Singleton 的觀念有兩點要注意的是</p>



<ol class="wp-block-list">
<li>Singleton 的作法其實就是 global variable 的改良。</li>



<li>Singleton 中其實可以放多個 instance. 此時 Singleton 就會多一個管理器的角色。</li>
</ol>



<p class="wp-block-paragraph">Singleton 實作上還有很多變化，上述只是基本精神，實際應用上應隨著系統需求而靈活變化才是。</p>



<h4 class="wp-block-heading">4. Builder</h4>



<p class="wp-block-paragraph">包含一個 <strong>director</strong> 和一個 <strong>builder</strong>。client 端擁有一個 director，builder 或以 reference 的形式存在在 director 端裡 (在 director construct 時)，或是當參數傳入。 </p>



<p class="wp-block-paragraph">底下是 client 端的 sample code</p>



<pre class="wp-block-code"><code>// ...
MyDirector1 myDirector1;
MyWorldBuilder builder;
myDirector1.createWorld(builder);
MyWorld world = builder.getWorld( );
// ...</code></pre>



<p class="wp-block-paragraph"><code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">MyWorldBuilder</mark></code> 可能有 <code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">buildTrees</mark></code>, <code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">buildHouses</mark></code>, <code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">buildRivers</mark></code> 等 method。以上例來說，<code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">MyDirector1</mark></code> 生成了一種世界，<code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">MyDirector2</mark></code> 則會生成另一種世界，with the same <code><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-cyan-blue-color">MyWorldBuilder</mark></code></p>



<p class="wp-block-paragraph">使用時機方面，當最終需求的 product 有如樂高一般可以由不同的 component 所組成時，可以使用此 pattern。director 的 creation function 可以選擇 create product part A and B, 或是 B and C, 或是其他組合。</p>



<h4 class="wp-block-heading">5. Prototype</h4>



<p class="wp-block-paragraph">Prototype pattern 最重要基本的精神就是使用 <strong>Clone method</strong> 把自己拷貝一份給 client。Client 需要 create prototype product 時，收到一個 prototype base class 的 pointer，調用 Clone method。</p>



<p class="wp-block-paragraph">同樣是 <strong>run-time</strong> 決定要生成哪一個 concrete product 的 design pattern，Prototype pattern 與吃參數的 factory method 差別在哪？</p>



<p class="wp-block-paragraph">以吃參數的 <strong>factory method</strong> 來說，client 會知道要生成哪一個 concrete product。因為通常 factory 會存在在 client 中，所以 factory method 的參數會經過 client。另外，client 也許也要確認 factory 是否支援此參數。</p>



<p class="wp-block-paragraph">以 <strong>Prototype pattern</strong> 來說，client 完全不知到目前要生成哪一個 concrete product，也沒有要確認任何 concrete product 相關正確性的責任。</p>



<p class="wp-block-paragraph">結論：<strong>Prototype pattern</strong> 會簡化系統 (client) 的設計與工作。但工作不會憑空消失，Prototype pattern 把相關的工作移到了類似 prototype manager 的模組去做。</p>



<p class="wp-block-paragraph">在一般情形中，我個人還是會使用<strong>吃參數的 factory method</strong>。但在生成物件極度動態的情形下 (Ex: 依照 config 不同而不同，依照 branch 不同而不同)，則會使用 Prototype pattern。</p>



<p class="wp-block-paragraph">最後實作時要注意的一點是，C++ copy constructor 是 <strong>member-wise copy</strong>。但是 Clone method 所需的是 <strong>deep copy</strong>，實作時要稍微注意一下。</p>



<p class="has-text-color wp-block-paragraph" style="color:#999999">[1] &#8220;Design Patterns&#8221;, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
