設計模式漫談之策略模式

最近也是事多,壓力也挺大的。煩事也多,因此又須要我寫篇博客靜靜心,最近看了不少asp.net底層代碼發現大牛真的多,天外有天人外有人。算法

想看底層代碼須要5年的工做經驗,精通語法,精通編程思想。而編程思想和語法能夠經過設計模式來學習。編程

 

在C語言中,能夠根據類型,申請內存空間。反射也是一樣的道理,根據類型申請空間。設計模式

 

接口至關於C語言中的申明,框架

也是一種封裝,好比,我須要A方法,B實現的時候,把A方法所須要的數據封裝隱藏.asp.net

 

封裝不一樣的狀況,提供統一接口,不管對象是關聯關係,仍是依賴關係,都是對象之間互相訪問(便可以找到對方的對象空間)。對象不銷燬,對象之中的數據仍在。ide

如今面向對象的框架大部分都是,工廠+反射+接口+代理。基本成套路了。直接上例子,我來解釋:函數

//抽象類,表面,我只須要你公開acceptCash(算法),程序即算法+數據,至於數據,我不須要你公開,你統一封裝隱藏。學習

abstract class CashSuper
{
public abstract double acceptCash(double money);
}this

//抽象的實現對象.net

class CashReturn : CashSuper
{

//始終不須要對外公開,可是對類內部公開
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
//構造函數
public CashReturn(string moneyCondition,string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}

重寫的對外公開類

public override double acceptCash(double money)
{
double result = money;
if (money >= moneyCondition)
result=money- Math.Floor(money / moneyCondition) * moneyReturn;

return result;
}
}

//上下文類。

//上下文意思是百曉生,百事通,知道全部的對象,那就須要能訪問到其餘對象的內存空間

class CashContext
{

//關聯對象,知道對象cs,對象不消亡,對象空間中的數據一直存在。
private CashSuper cs;

public void setBehavior(CashSuper csuper)
{
this.cs = csuper;
}

//又對外統一提供接口

public double GetResult(double money)
{
return cs.acceptCash(money);
}
}

//客戶端(如今系統的模型有事件模型,數據模型,請求處理響應模型等)

CashContext cc = new CashContext();

DataRow dr = ((DataRow[])ds.Tables[0].Select("name='" + cbxType.SelectedItem.ToString()+"'"))[0];
//反射的參數是object[]
object[] args =null;

if (dr["para"].ToString() != "")
args = dr["para"].ToString().Split(',');

cc.setBehavior((CashSuper)Assembly.Load("商場管理軟件").CreateInstance("商場管理軟件." + dr["class"].ToString(), false, BindingFlags.Default, null, args, null, null));

double totalPrices = 0d;

//調上下文的統一接口
totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text));
total = total + totalPrices;
lbxList.Items.Add("單價:" + txtPrice.Text + " 數量:" + txtNum.Text + " "+cbxType.SelectedItem+ " 合計:" + totalPrices.ToString());
lblResult.Text = total.ToString();

 

總結,策略模式就是抽象,接口,反射的具體應用。根據不一樣的策略生成不一樣的對象,調用多態的方法。

 

編程思想,能夠從設計模式中學到,也能從設計模式中學到一種語言的語法。

 

睡覺了,不寫了。下次見!

相關文章
相關標籤/搜索