用一套方法論去設計許多方法來解決工程上遇到的問題。 即 "一生萬法、萬法圓通"。

Recent in Recipes

3/Food/post-list
顯示具有 programming 標籤的文章。 顯示所有文章
顯示具有 programming 標籤的文章。 顯示所有文章

編程技巧進階修練 -- Python 篇

1. OOP (物件導向)

2. Refactoring (重構並簡化)

3. Pythonic Style (善用Python獨門技巧)

4. Comprehensive Application(全面的應用範例)


1. OOP (物件導向)



2. Refactoring (重構並簡化它)




3.Pythonic Style (善用Python獨門技巧)





4.Comprehensive Application(全面的應用範例)



DP2 建造者模式 Builder

 1. factory method


2. Builder


DP1 抽象工廠 Section1.2 Abstract Factory

 代碼布局(佈陣)


1. FrogWorld 和 WizardWorld 代表抽象工廠。因為是Python的關係,所以它把上一階應該要有的Interface約定省略掉了,而透過 make_character 和 make_obstacle 來實作共同的接口。 In a statically typed language, the Abstract Factory would be an abstract class/interface with empty methods, but in Python this is not required because the types are checked in runtime. (因為對Python定義一個空的Class 是沒有實質意義的)
2. The GameEnvironment is the main entry point of our game. It accepts factory as an input, and uses it to create the world of the game. 
3. The play() method initiates the interaction between the created hero and the obstacle







DP1 工廠方法 Section1.1 Factory Method

1. 對於代碼分類和包裝的實用技巧,使它看起來簡潔、優雅。

2. 透過一個工廠方法(connection_factory)去生成一個(產品)實例,而不是用hardcode的方式去生成一個實例。The connection_factory() function is a Factory Method. It returns an instance of  JSON Connector or XMLConnector depending on the extension of the input file path

3.這個方法附帶了生成的條件(if-elif condition), 因此產生了彈性。

4.再把這個方法在包裝一層例外處理的機制,使這個功能加穩固。

5.用來確認異常處理是否有效

6.透過XPath用來匹配符合條件的資料筆(Record)

查找所有包含姓(last name)为 Liar 的 person 元素。对于每个匹配到的元素,展示其基本的姓名和电话号码信息

7.這裡沒有條件匹配,所有的資料筆(Record)都會被掃出來


重點問題思考:

1. 還有哪些重複相同的代碼可以歸納收斂?

2.即使假設可以使用相同的代碼來處理XML和JSON文件,當需要支持第三種格式(例如,SQLite)時,又該對代碼作哪些改變呢?找一個SQlite文件或者自己創建一個,嘗試一下。

3. 像現在這樣,代碼並未禁止直接實例化一個連接器。如果要禁止直接實例化,是否可以實現?試試看。 就是說我們規定只能透過函式產生實例,而不能直接調用類別產生實例?


參考資料:

簡單工廠模式 和 工廠方法模式 的優缺點 

簡單工廠模式 (Simple Factory Pattern)

OO Class Diagram 類別圖