6/29/2011

Build Strategy Pattern

繼上一篇Strategy Pattern 討論到程式碼並不完美,主要缺失必須要瞭解每個算法與Context才能自在使用。比較好處理方式可將Context包裝成CompressionFactory或CompressionService方便其他人呼叫使用,但如何去建構?

自行撰寫雖然也不是問題,但似乎太浪費時間在處理此細節。

Tapestry IoC framework提供 StrategyBuilder 容易建立Strategy Pattern

A service implementation builder that operates around a StrategyRegistry, implementing a version of the Gang of Four Strategy pattern. The constructed service is configured with a number of adapters (that implement the same service interface). Method invocations on the service are routed to one of the adapters.

6/28/2011

Strategy Pattern

策略模式(Strategy Pattern)根據不同的環境條件,選擇最適當演算法(一組同性質算法)來使用。

wikipedia Strategy pattern

the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.[1]

策略模式算日常開發滿常使用模式,尤其是做專案時,使用者常常會開出這樣子需求, 根據{A -> A_activity, B -> B_activity, C -> C_activity...}對於這些{A, B, C...}_activity幾乎非常相似應該也可說是同性質活動,同時還要求日後可擴充。

最常見的範例 每一種不同產品{book, nb, pc...}類型有不同折扣數;不同的壓縮{zip, rar, gz...}有不同的壓縮算法;不同的檔案格式{doc, exe, xls...}有不同的處理邏輯等。

所以可定義有一組同性質算法,並將每種算法封裝起來,讓它們可根據不同的條件來互換使用。

策略模式結構:

strategy pattern

6/22/2011

使用多個相同Polymorphic Association無法解決在相同的Model

這個問題滿難解釋,在Rails一個model下同時使用多個相同Polymorphic Association,似乎無法解決問題。

情況如下

[code lang="ruby"] class Article < ActiveRecord::Base   has_one :header_image, :as => :imageable   has_many :images, :as => :imageable end [/code]

:header_image, :images無法區隔imageable_type資訊 (imageable_type = "Article")

G大神問了一下+看了一下ActiveRecord 程式,確實無法解決,只能繞路走 single table inheritance 雖然不是我要,但是只少可以解決問題。

有空來想看看可不可以提一個 patch!

6/03/2011

Java 異質系統整合

最近幫了某家線上音樂公司開發音樂自動化轉檔需求,其中之一功能需求來至四面八方唱片業所倒檔過來資料{xml, music files}。當然系統內部已經有自已統一介面 (interface)去接來至外面倒檔,但是如何處理煩雜的來源?

整理實作問題

  1. 每家XML似乎都是不同的格式,其中有幾家有使用DDEX( Digital Data Exchange)
  2. 每家XML內容龐大
  3. 如何花最小成本開發 (資源極有限)
  4. 日後好維護前提(Orz)

選擇方案

  1. XML Parser
  2. 不管用什麼方法都是累,要摘錄資訊真的太多!

  3. Java Architecture for XML Binding (JAXB)
  4. 想法 XML <-> Binding (Schema) <-> Java

    Sun JAXB

初步實作細節

  1. XML Binding
  2. [code lang="java"] xjc工具可以把schema 自動產生對應java類別 xjc ddex.xsd [/code]

    xjc 有些物件產生並不如預期,只能硬改所產生Code

  3. Transform to java object
  4. [code lang="java"] JAXBContext jc = JAXBContext.newInstance("net.ddex.xml._2010.ern_main._32"); Unmarshaller u = jc.createUnmarshaller(); return (NewReleaseMessage) u.unmarshal(inputStream); [/code]
  5. to business domain
  6. [code lang="java"] 轉換內部系統business domain [/code]

目前架構已經上線了,維護及開發都滿符合預期。