機房重構 策略模式

2021-07-11 02:14:51 字數 2731 閱讀 5215

剛開始學習策略模式的時候雖然書是看懂了但是有乙個問題就是不知道如何去實際的應用,通過機房重構中下機消費金額的計算懂得了如何的去使用這個策略模式。

它定義了演算法家族,分別封裝起來,讓它們之間可以互相替換,此模式讓演算法的變法,不會影響到使用演算法的客戶。

dim cashsuper as bc_cashsuper '定義抽象類

public sub new(byval cardtype as string) '引數是收費型別

select case cardtype

case "固定使用者"

cashsuper = new bc_cashvip() '建立固定使用者收費型別

case "臨時使用者"

cashsuper = new bc_cashnormal() '臨時使用者收費

case else

cardtype = nothing

end select

end sub

public function getresult(byval time as integer) as single

'呼叫相關的消費處理類計算收費方法

return cashsuper.getconsumemoney(time)

end function

end class

public mustinherit class bc_cashsuper

public mustoverride function getconsumemoney(byval time as integer) as single 『處理請求的抽象方法

end class

public class bc_cashnormal : inherits bc_cashsuper

dim enbasicinfo as new entity.basicinfo '定義實體

dim table as new datatable

dim baseinfo as new bll.bbasicinfo '用於查詢基礎資料

dim norcash as single

public overrides function getconsumemoney(time as integer) as single

'呼叫查詢方法獲取資料,且賦值給實體泛型集合

table = baseinfo.checklimitcash1(enbasicinfo)

enbasicinfo.rate = table.rows(0).item(1) '給變數賦值(使用者每小時費用)

norcash = cint(enbasicinfo.rate)

dim consumecash as single

consumecash = trim(csng(time) * csng(norcash / 60))

return consumecash

end function

end class

public class bc_cashvip : inherits bc_cashsuper

'呼叫查詢方法獲取資料,且賦值給實體泛型集合

dim baseinfo as new bll.bbasicinfo '用於查詢基礎資料

dim enbasicinfo as new entity.basicinfo '定義實體

dim table as datatable

'定義實體泛型

dim vipcash as single '定義變數存放固定使用者每小時費用

public overrides function getconsumemoney(time as integer) as single

table = baseinfo.checklimitcash1(enbasicinfo)

enbasicinfo.rate = table.rows(0).item(0) '給變數賦值(使用者每小時費用)

vipcash = cint(enbasicinfo.rate)

dim consumecash as single

consumecash = trim(csng(time) * (vipcash / 60)) '計算消費金額

return consumecash

end function

end class

'計算消費的金額, 將消費時間傳入 呼叫策略模式

dim cashcontext as new bll.bc_cashcontext(father.type.trim)

onlineinfo1.consumetime = txtcumetime.text.tostring

dim consumecash as single = cashcontext.getresult(onlineinfo1.consumetime)

使用策略模式為我們省了很多的時間,簡化了**量,最主要的還是簡化了單元測試,因為每個演算法都有自己的類,可以通過自己的介面單獨測試。

機房重構 下機 職責鏈模式 策略模式(理論篇)

第一次機房收費系統的時候,我們側重於功能的實現,對於大範圍的使用if.else,沒有太明顯的感覺。可當我們學完設計模式之後,才發現原來多次使用if.else,會使程式產生很高的耦合性,不便修改。對於同樣的下機內容,我們除了要用到七層的知識,可能最大的收穫就是去學習如何把設計模式運用到實踐中去了。1 ...

機房重構 上下機(職責鏈模式和策略模式)

機房重構中上機功能相對好實現一些,下機用到了職責鏈模式和策略模式,職責鏈模式算時間,策略模式算消費金額 部分 dal層 public class offdal ioffidal string sql select from card where cardno cardno datatable tab...

機房重構利用策略模式 簡單工廠實現消費金額的計算

在做第一次機房收費系統中。有一項非常令人頭疼的事情,那就是暫時使用者的問題,在結賬的時候,我們需要考慮該使用者是固定使用者還是暫時使用者,原來在用vb6.0做的時候,假設我們實現了這個功能,那麼在 中會出現非常多的if.else 語句,同一時候。我們必需要呼叫資料設定視窗中的資料。這種話,會非常麻煩...